gpt4 book ai didi

javascript - 当对象更新超出范围时如何更新 angularJS 中的 View

转载 作者:行者123 更新时间:2023-11-28 02:28:15 28 4
gpt4 key购买 nike

我有一个在 AngularJS 范围之外的对象,看起来像:

obj = { isBig : true, name: "John" ... }

它有很多参数,它是在 Angular 范围之外创建的,并且在 AngularJS 之外更新(例如 - 通过我使用 jQuery 进行的 ajax 调用)。

在我的 Controller 中我写:

$scope.obj = obj;

如何创建一个事件来监听任何对象的更改并更新 View ?所以事件就是对象的变化

具体来说,我有一个名为 obj.isAjaxCallFailed = true/false 的参数我在 View 中使用 <div ng-show="obj.isAjaxCallFailed"></div>

它不工作。我尝试使用 $on我想不出任何方法来做到这一点。

最佳答案

使用$watch()obj监听更改(在您的 Controller 中):

$scope.$watch(function() {
return obj;
}, function(value) {
if(value) {
$scope.obj = obj;
}
}, true);

在代码中创建或更新 obj 的位置,您使用$rootScope.$apply()启动 watch :

function someCallbackOutsideAngular(data) {
var $rootScope = angular.injector(['ng']).get('$rootScope');
$rootScope.$apply(function() {
obj.someKey = data.someValue;
});
}

注:angular.injector(['ng'])也许应该在回调之外的某个地方设置(不需要一直执行它)。

关于javascript - 当对象更新超出范围时如何更新 angularJS 中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com