假設您在作用域中有一個對象數組,並且您想用指令更新它。我怎樣才能做到這一點 ?我不確定應該怎麼做。使用衛星數據更新範圍
重點是我想更新範圍名稱和「衛星數據」,這是在這種情況下的id,但我們可以想象,我們有更多的。
問題:爲什麼我需要一個id值,如果我不打算在UI中顯示它呢?想象一下,相反,我們正在與一個數據庫交談,並且數據庫正在根據輸入值+相應的ID返回一個值。這個id將在提交表單時被使用。
還有一件事:我們不想直接訪問指令中的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};
}
}
};
});
是的。假設我們不想直接修改指令中的people變量,你會怎麼做?在屬性中附加一個函數? – JohnCastle 2013-04-23 07:26:14
是的。將數據作爲參數發送。 – Ketan 2013-04-23 15:17:12