Using ng-model on a resolved promise in AngularJS

2019-09-15 02:43发布

问题:

Here's my simple controller and directive:

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">',
    };
});

The scope item is resolved from a promise. When I use ng-model in the HTML, why doesn't the input update the item, and why won't the directive even let me type?

See this fiddle for a working example: http://jsfiddle.net/winduptoy/XmBxK/

回答1:

I think what is going on is that every time you type into an input box Angular's digest loop examines the result of the promise and reassigns myObject to $scope.item. Here's one way to avoid that:

//$scope.item = itemDeferred.promise;
var promise = itemDeferred.promise;

promise.then(function(obj) {
   alert('Success: ' + obj);
   $scope.item = obj;
}, function(reason) {
   alert('Failed: ' + reason);
});

Fiddle.