スコープ内にオブジェクトの配列があり、それをディレクティブで更新したいとします。どうやってやるの ?何をすべきかよくわかりません。
要点は、この場合は ID である名前と「衛星データ」でスコープを更新したいということですが、それ以上のものがあると想像できます。
質問: わざわざ UI に表示しないのに、なぜ id 値が必要なのですか? 代わりに、データベースと対話していて、データベースが入力値 + 対応する ID に基づいて値を返していると想像してください。この ID は、たとえばフォームを送信するときに使用されます。
もう 1 つ: ディレクティブから people 変数に直接アクセスしたくありません。ディレクティブが一般的ではないためです。ここにプランクを作成しました: 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};
}
}
};
});