如果相反,我将记录包装在数组中并使用ng:repeat进行迭代,表单正确绑定,我可以编辑值.
我创建了一个显示问题的plnkr:
http://embed.plnkr.co/fOWyhVUfekRbKUSRf7ut/preview
您可以编辑直接绑定和列表绑定的输入字段,但是绑定到单个承诺的字段不能被编辑.
可以将ng:model直接绑定到从承诺返回的对象,还是需要使用数组才能使其工作?
app.controller('MainCtrl',function($scope,$timeout,$q) {
var person = {"name": "Bill Gates"}
var deferList = $q.defer();
var deferSingle = $q.defer();
// Bind the person object directly to the scope. This is editable.
$scope.direct = person;
// Bind a promise to the scope that will return a list of people. This is editable.
$scope.list = deferList.promise;
// Bind ap romise to the scope that will return a single person record. This is *not* editable.
$scope.single = deferSingle.promise;
// Resolve the promises
$timeout( function(){
deferList.resolve( [person] ); // Array
deferSingle.resolve( person ); // Just the record itself
},100);
});
<body ng-controller="MainCtrl">
Directly Bound - This field is editable
<input ng:model="direct.name"/>
<hr/>
Singleton Promise - This field is *not* editable.
<input ng:model="single.name"/>
<hr/>
List Promise: - This field is editable
<div ng:repeat="person in list">
<input ng:model="person.name"/>
</div>
</body>
编辑:经过一些调试,我发现ng:model指令正在从promise的值(‘$$v’)组件读取,而是直接写入promise对象本身.
当尝试编辑承诺时,viewmodel将不断地恢复为原始值,同时在承诺本身上存储字符.因此,如果用户在输入字段中键入“asdf”,结果将如下.
{Name: "Asdf",$$v: {Name: "Bill Gates"}}
而我们应该期待
{$$v: {Name: "asdf"}}
我做错了,还是AngularJS中的这个bug?
(为了进一步澄清,问题是数组和承诺返回的对象之间的行为差异,直接绑定只是一个控件)
解决方法
看来AngularJS 1.0.3引入了这个问题:
http://jsfiddle.net/sonicsage/k8W4Y/6/
如果您切换到AngularJS 1.0.2,它将工作.
GitHub有一个公开的问题:https://github.com/angular/angular.js/issues/1827
原来的线程在Google Groups.
还有一个有趣的线程关于自动解包在这里:
https://github.com/angular/angular.js/pull/1676
通过在Chrome控制台中调试应用程序,您可以看到单个是一个函数(承诺):
> $('body.ng-scope').data('$scope').single
Object {then: function,$$v: Object}
$$v: Object
then: function (b,g){var j=e(),h=
__proto__: Object
而直接是一个对象:
> $('body.ng-scope').data('$scope').direct
Object {name: "Bill Gates",$$hashKey: "004"}
然而,按下只读输入上的键对承诺有影响,例如,选择所有文本并将其删除,虽然对UI没有任何影响,但对该属性有影响:
> $('body.ng-scope').data('$scope').single.name
""
您可以在这里进一步调试应用程序:http://run.plnkr.co/plunks/rDo7bFZlBq4rRH2ZNJn1/
编辑
IMO直接约束一个领域的承诺是不支持的(这是正式记录吗?),更改代码如下将工作:
// Bind ap romise to the scope that will return a single person record. This is *not* editable.
deferSingle.promise.then(function(data) {
$scope.single = data;
},function(data) {
// error
});
这是广告牌:http://run.plnkr.co/plunks/rDo7bFZlBq4rRH2ZNJn1/