我想要偵聽對象數組中每個對象的特定屬性,並根據更改的屬性更改對象中的另一個屬性值。我正在使用Angular材質的md-select來更改屬性值。到目前爲止,我嘗試瞭如下。但它不起作用。我哪裏錯了?請幫忙。觀察對象數組中每個對象的特定屬性 - 角度素材
app.js
var app = angular.module('app', ['ngAria', 'ngAnimate','ngMaterial']);
app.controller('appController', function ($scope) {
$scope.modes = [{id: 1}, {id: 2}, {id: 3}];
$scope.items = [
{id: "1", text: "word", textMode: {id: 1}},
{id: "2", text: "word", textMode: {id: 1}},
{id: "3", text: "word", textMode: {id: 1}}
];
angular.forEach($scope.items, function(item) {
$scope.$watch('item.textMode.id', function() {
if (item.textMode.id === 1) {
item.text = "word";
} else if (item.textMode.id === 2) {
item.text = "phrase";
} else if (item.textMode.id === 3) {
item.text = "paragraph";
}
})
});
});
的index.html
<div ng-app="app">
<div ng-controller="appController">
<div ng-repeat="item in items">
<md-select aria-label="textChanger" class="selector" ng-model="item.textMode.id" placeholder="Text mode ID">
<md-option ng-repeat="mode in modes" ng-value="mode.id">
{{mode.id}}
</md-option>
</md-select>
<br>
{{item.text}}
<br><br><br>
</div>
</div>
</div>
JsFiddle: https://jsfiddle.net/lpsandaruwan/ho5egr16/
沒有angular.js的experiance,但你的功能將不觸發下拉值更改時 – Ionut
用$ watchCollection代替$ watch。此外,我認爲你應該簡化你的物品對象,一些屬性似乎是多餘的。 –