javascript – 当范围更改时,AngularJS不更新模板变量

这将是专家们非常明显的愚蠢问题之一.

我有一个websocket将数据推送到我正在尝试存储数据的服务,并通过我的控制器将其推送到模板.

数据进来并更新变量,但UI仅更新是对该数据执行操作:

services.factory('Summary', ['$q','$rootScope','$http', '$location', function ($q, $rootScope,$http, $location) {

var Service = {};
Service.dataObj = {};
Service.dataObj.d = {"gello":"goodbye"};
....
function listener(data) {
   messageObj = data;
    Service.dataObj.d = data;
  console.log("Received data from websocket: ", messageObj);

}
})]);


controllers.controller('UserCtrl', ['$scope', 'Summary',
function ($scope, Summary) {

    $scope.click = function(){
        alert(JSON.stringify($scope.summaryinfo));
    }
    $scope.summaryinfo = [Summary.dataObj];
    $scope.summarygridOptions = {
        data: 'summaryinfo'
    };
    console.log("hello");
}]);

数据被抽入,并且据我所知,因为它被存储在Service.dataObj.d中,如果我将我的HTML模板指向Service.dataObj,该对象正被更新而不被替换,因此指针应保留并且该对象被监视.

但是,除非我运行click()方法,否则UI会受到影响,即使只是触发警报,也不会改变.

我失踪了什么

你可能需要使用$apply()

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).

function listener(data) {
   $scope.$apply(function() {
       Service.dataObj.d = data;
   });
}
翻译自:https://stackoverflow.com/questions/20954401/angularjs-not-updating-template-variable-when-scope-changes

转载注明原文:javascript – 当范围更改时,AngularJS不更新模板变量