javascript 范围更改时,AngularJS 不更新模板变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20954401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS not updating template variable when scope changes
提问by bugg_tb
This will be one of those stupid questions that is very obvious to the experts.
这将是专家们非常清楚的愚蠢问题之一。
I have a websocket pushing data to a service where I'm trying to store the data and have it pushed to a template via my controller.
我有一个 websocket 将数据推送到一个服务,我试图在其中存储数据并通过我的控制器将其推送到模板。
The data is coming in and updating the variable but the UI only updates is I perform a action on that data:
数据正在传入并更新变量,但 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");
}]);
The data gets pumped in and as far as I was aware because its being stored in Service.dataObj.d if I point my HTML template at Service.dataObj that object is being updated and not replaced so the pointer should remain and the object be watched.
数据被泵入,据我所知,因为它存储在 Service.dataObj.d 中,如果我将我的 HTML 模板指向 Service.dataObj,该对象正在更新而不是被替换,因此应该保留指针并监视该对象.
But it doesn't change unless I run the click() method, in which case the UI is affected even though Im just triggering an alert.
但是除非我运行 click() 方法,否则它不会改变,在这种情况下,即使我只是触发警报,UI 也会受到影响。
What am I missing?
我错过了什么?
回答by JB Nizet
You probably need to use $apply()
:
您可能需要使用$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).
$apply() 用于从 angular 框架之外执行 angular 表达式。(例如来自浏览器 DOM 事件、setTimeout、XHR 或第三方库)。
function listener(data) {
$scope.$apply(function() {
Service.dataObj.d = data;
});
}