这是我的简单控制器和指令:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope, $q) {
var myObject = {
name: "Dingus",
favoriteFood: "Chicken",
};
var itemDeferred = $q.defer();
$scope.item = itemDeferred.promise;
var resolveIt = function() {
itemDeferred.resolve(myObject);
};
resolveIt();
}
myApp.directive('promised', function() {
return {
restrict: 'E',
scope: { boundModel: '=' },
template: '<input type="text" ng-model="boundModel">',
};
});
范围项从承诺中解析。当我在HTML中使用ng-model
时,为什么输入不会更新项目,为什么指令甚至不允许我输入?
请参阅此小提琴,了解一个工作示例:http://jsfiddle.net/winduptoy/XmBxK/
答案 0 :(得分:3)
我认为发生的事情是每次输入输入框时,Angular的摘要循环会检查promise的结果并将myObject重新分配给$ scope.item。这是避免这种情况的一种方法:
//$scope.item = itemDeferred.promise;
var promise = itemDeferred.promise;
promise.then(function(obj) {
alert('Success: ' + obj);
$scope.item = obj;
}, function(reason) {
alert('Failed: ' + reason);
});