Watching subvalues of array

我的梦境 提交于 2019-12-11 10:37:57

问题


I have a dynamic array with items, which could look like this:

$scope.items = [
    {id: 1, name: 'Ford', checked: false},
    {id: 2, name: 'Mercedes', checked: true},
    {id: 3, name: 'BMW', checked: false}
];  

I want to react whenever a checked value is changed, and know which item it was changed on.

How can I achieve this?


回答1:


You could register an ng-change event to the check boxes bound. If you indeed really want to add a watch you can use the deep watch option. $scope.$watch('items', fn, true). However i will not to use a watcher unless it is absolutely required.

Example:-

<label ng-repeat="item in items track by item.id">
<input type="checkbox" ng-model="item.checked" ng-change="carSelected(item)" />{{item.name}}</label>

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.items = [{
    id: 1,
    name: 'Ford',
    checked: false
  }, {
    id: 2,
    name: 'Mercedes',
    checked: true
  }, {
    id: 3,
    name: 'BMW',
    checked: false
  }];

  $scope.carSelected = function(item) {
    //Do something with the selected
    console.log(item);
  }
  
  $scope.$watch('items', function(){
    console.log("Item updated");
  }, true)
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <label ng-repeat="item in items track by item.id">
    <input type="checkbox" ng-model="item.checked" ng-change="carSelected(item)" />{{item.name}}</label>
  <p>
    {{items}}
</div>


来源:https://stackoverflow.com/questions/28000795/watching-subvalues-of-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!