假设您的作用域中有一个对象数组,并且您想使用指令对其进行更新。我怎样才能做到这一点 ?我不确定应该怎么做。
要点是我想用名称和“卫星数据”更新范围,在这种情况下是 id,但我们可以想象我们有更多。
问题:如果我不费心在 UI 中显示它,为什么我仍然需要一个 id 值?想象一下,我们正在与数据库交谈,并且数据库正在返回一个基于输入值 + 相应 id 的值。例如,在提交表单时将使用此 ID。
还有一件事:我们不想直接访问指令中的 people 变量,因为这样指令就不是通用的。我在这里创建了一个 plunk:http: //plnkr.co/edit/D2ybe8uPSdzeIxTFzad5
HTML 文件:
<body ng-controller="MainCtrl">
<span ng-repeat="val in people">
<input customattr type = "text" ng-model="val.name" />
<br /> <br/> Children :
<span ng-repeat="v in val.children">
<input customattr type = "text" ng-model="v.name" />
</span>
</span>
</body>
JS文件:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.people = [{"name":"Toto", "id":1,
"children": [
{"name":"John","id":2},
{"name":"Mary","id":3}
]
}];
});
app.directive('customattr', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element[0].onblur = function() {
console.log("Hello there" + element[0].value);
// make some magic processing of the input with a XHR request here...
// for the demonstration the XHR request is replaced by findTheNewDict
var newDict = findTheNewDict(element[0].value);
console.log(newDict);
// Now we want to update the scope with the data
// How can we do that ?
scope.$apply(function(s) {
// We have no knowledge of the variable people here
// We just know that the data is a dict containing a name and an id
});
}
findTheNewDict = function(input) {
// Just a dummy return : it doesn't matter what is returned
// The main point is that I want to update the right variable
// in the scope with this data
return {"name": input + "a", "id":input.length};
}
}
};
});