javascript - 观察对象数组中每个对象的特定属性 - Angular Material

标签 javascript angularjs angular-material

我想监听对象数组中每个对象的特定属性,并根据变化的属性更改对象中的另一个属性值。我正在使用 Angular Material 的 md-select 来更改属性值。到目前为止,我已尝试如下。但它不起作用。我哪里出错了?请帮忙。

应用程序.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/

最佳答案

试试这个 JavaScript/AngularJS Controller 调整:

  $scope.$watch('items', function(newValues, oldValues) {
    for (var i = 0; i < newValues.length; i++) {
      if (newValues[i].textMode.id === 1) {
        newValues[i].text = "word";
      } else if (newValues[i].textMode.id === 2) {
        newValues[i].text = "phrase";
      } else if (newValues[i].textMode.id === 3) {
        newValues[i].text = "paragraph";
      }
    }
  }, true);

诀窍是用 $watch 中的 'true' 观察对象数组的属性变化(深度观察)。

这是您的 JSFiddle 更新,https://jsfiddle.net/rekrah/vndf0hcu/ .

关于javascript - 观察对象数组中每个对象的特定属性 - Angular Material ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42420308/

相关文章:

javascript - 输入值改变时改变背景图片

angularjs - 使用同一 Controller 在两个 div 之间共享数据

javascript - 将 Object.setPrototypeOf 与 instanceof 一起使用

javascript - 通过别名获取 Javascript 字符串变量的值

javascript - AngularJS 中多个 ng-app 的通用 Controller

html - Angular Material 布局对齐 = "center center"不工作

angular - 垫日历 : Display only month and year

html - flex 布局(使用 Angular Material )在某些平台上中断

javascript - Angular bootstrap-ui,不显示字形

javascript - 如何在 Javascript 数组中添加 HTML 标记