我正在使用 angularjs,我对 ng-model update 有一个小问题。
我有一个 $scope 对象,它在服务中的 ng-controller 之外加载了 ajax。
服务如下:
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 对象已更新。
现在我需要在 html 页面的输入文本中更新和显示值,它具有更新对象的 ng-model 属性,如下所示:
<input type="text" name="totalInvitations"
ng-model="invitation.totalInvitations" required smart-float/>
但是,当我执行 $scope.safeApply() 函数时(我使用 safeApply 来防止“$digest already in progress error”),ng-model 没有任何变化。
这是我的 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 和显示值?
谢谢
最佳答案
看起来这里的大部分内容都是正确的,我假设您调试后看到它命中了这一行:
$scope.invitation = d;
如果是这种情况,我唯一能看到的错误是靠近顶部定义的 HTML 元素没有包含在定义 Controller 的区域内。
<div ng-controller="editInvitationCtrl>
<input type="text" name="totalInvitations"
ng-model="invitation.totalInvitations" required smart-float/>
</div>
关于javascript - Angularjs:对象更改后 ng-model 不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17197349/