[英]AngularJS scope variables not updating in jQuery promise/deferred
我正在AngularJS
上构建一个单页应用程序,并且我设置了一个controller
该controller
具有单击按钮时运行的功能。 该功能运行良好。 函数解析后,我将更新根变量并更改$location
路径。 但是根变量和$location
似乎没有更新。
请注意,所有代码均来自生产示例
DOM:
<div ng-controller="ExampleController">
<button ng-click="button_function('I am a variable')">Run function</button>
</div>
控制器:
app.controller('ExampleController', ['$scope', '$location', function($scope, $location) {
$scope.button_function = function(variable) {
$scope.$root.show_something = true;
my_function.something(variable).done(function(data) {
if (data) {
$scope.$root.show_something = false;
$location.path('/go-to-path');
} else {
alert('Something went wrong');
}
}]);
};
}]);
这是my_function
代码:
var my_function = {
something: function(variable) {
var deferred = $.Deferred();
var window = window.open('http://dynamic.url/', '_blank');
$(window).on('loadstart', function(e) {
var url = e.originalEvent.url;
if (url === 'http://dynamic.url/expected_response') {
window.close();
deferred.resolve({
key_1: 'data',
key_2: 'more data'
});
}
});
return deferred.promise();
}
};
看起来都不错吧? 但是,当my_function.something(variable)
被“完成”时, $location
和$scope.$root.show_something
似乎没有更新。
难道我做错了什么?
谢谢
您应该返回deferred.promise
而不是deferred.promise()
。
--edit:不好意思,我没有看到您因为误读而没有使用$ q。
我找到了解决方法。
在我的控制器中,“ deferred
”完成后,我将变量包装在$timeout
app.controller('ExampleController', ['$scope', '$location', '$timeout', function($scope, $location, $timeout) {
$scope.button_function = function(variable) {
$scope.$root.show_something = true;
my_function.something(variable).done(function(data) {
if (data) {
$timeout(function() {
$scope.$root.show_something = false;
$location.path('/go-to-path');
}, 1);
} else {
alert('Something went wrong');
}
}]);
};
}]);
在这里找到答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.