【发布时间】:2013-06-19 17:14:22
【问题描述】:
我正在使用 angularjs,但我在更新 ng-model 时遇到了一点问题。
我有一个 $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 错误”),ng-model 没有任何变化。
这是我的 ng 控制器:
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 和显示值需要什么?
谢谢
【问题讨论】:
-
另外关于 safeApply 不确定您使用的是哪个版本的 Angular 但我还没有遇到您所指的错误,使用了 1.0.7 和 1.1.4 您使用的是什么版本?这是一个长期存在的问题吗?
-
你的代码在这个小提琴中工作:jsfiddle.net/bcaudan/PVmG6,我只用 $timeout 替换 $http 发送虚假响应。
-
感谢所有回答,这是在外部 div 中声明的 ng-controller 的问题。现在一切正常
标签: javascript angularjs angularjs-scope