在AngularJS一个解决承诺使用NG-模型(奇怪的行为) [英] Using ng-model on a resolved promise in AngularJS (strange behavior)

查看:93
本文介绍了在AngularJS一个解决承诺使用NG-模型(奇怪的行为)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我简单的控制器和指令:

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

范围项目从一个承诺解决。当我在HTML中使用 NG-模型,为什么不输入更新的项目,为何不将指令竟然让我键入?

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?

请参阅此捣鼓工作示例: http://jsfiddle.net/winduptoy/XmBxK/

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

推荐答案

我认为正在发生的事情是,每次你键入一个输入框角的消化循环检查承诺的结果,并重新分配给myObject的$ scope.item 。下面是避免一种方式:

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);
});

小提琴

这篇关于在AngularJS一个解决承诺使用NG-模型(奇怪的行为)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆