AngularJS:对象更改后ng-model不刷新 [英] Angularjs: ng-model doesn't refresh after object change
问题描述
我正在使用angularjs,但ng-model更新有一些问题.
I'm working with angularjs and I have a little problem with ng-model update.
我有一个$ scope对象,该对象在服务中的ng-controller外部加载了ajax.
I have a $scope object that is loaded with ajax outside of the ng-controller, in a service.
该服务如下:
app.factory('myService', function($http) {
var myService = {
async: function(code) {
var promise = $http.get(url).then(function (response) {
return response.data;
});
return promise;
}
};
return myService;
});
这有效,并且更新了ng-controller中的$ scope对象.
This works, and my $scope object in ng-controller is updated.
现在我需要更新并在html页面的输入文本中显示该值,该文本具有我更新后的对象的ng-model属性,如下所示:
Now i need to update and show the value in an input text in html page, that have the ng-model attribute of my updated object, like this:
<input type="text" name="totalInvitations"
ng-model="invitation.totalInvitations" required smart-float/>
但是,当我执行$ scope.safeApply()函数(我使用safeApply来防止"$ digest已经进行错误")时,ng-model不变.
But, when I perform $scope.safeApply() function (I use safeApply to prevent "$digest already in progress error") nothing change in ng-model.
这是我的ng-controller:
Here is my ng-controller:
function editInvitationCtrl(myService, $scope, $http) {
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
console.log(phase);
}
} else {
console.log("apply");
this.$apply(fn);
}
};
myService.async($scope.code).then(function(d) {
$scope.invitation = d;
$scope.safeApply(function(){
console.log(JSON.stringify($scope.invitation));
});
});
我做错了什么?
我需要更新ng-model和显示值吗?
What I need to update ng-model and show values?
谢谢
推荐答案
看起来这里的大多数内容都是正确的,并且我假设您已调试以查看它是否符合以下条件:
It looks like most everything here is right, and I assume you debugged to see that it hit this line:
$scope.invitation = d;
如果是这种情况,我唯一能看到的错误是顶部附近定义的HTML元素未包装在定义控制器的区域内.
If that's the case the only thing I could see being wrong is that the HTML element defined near the top isn't wrapped within the area the controller is defined.
<div ng-controller="editInvitationCtrl>
<input type="text" name="totalInvitations"
ng-model="invitation.totalInvitations" required smart-float/>
</div>
这篇关于AngularJS:对象更改后ng-model不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!