AngularJS watch an object property in an object array

后端 未结 4 1561
日久生厌
日久生厌 2021-02-06 20:56

I have this data in my controller

    $scope.data = {
        home: {
            baseValue: \"1\",
            name: \"home\"
        },
        co         


        
相关标签:
4条回答
  • 2021-02-06 21:11

    You can watch an object attribute.
    So you can do something like

    for(var key in $scope.data) {
      if($scope.data.hasOwnProperty(key)) {
        $scope.$watch("data['" + key + "'].baseValue", function(val, oldVal) {
          // Do stuff
        });
      }
    }
    

    Not tested, but the idea is simple.

    0 讨论(0)
  • 2021-02-06 21:17

    Based on your question, you can use ngChange to watch changes of baseValue and trigger the function.

    HTML

    <section class="content row" ng-repeat="item in data">
        Name: {{item.name}} <br/>
        BaseValue: <input type="text" ng-model="item.baseValue" ng-change="baseValueChange(item.baseValue)"/>
    </section>
    

    Controller

    $scope.baseValueChange = function(baseValue) {
        console.log("base value change", baseValue);
    }
    

    If you a more sophisticated version which can get oldValue and newValue, you can refer to this plunkr - http://plnkr.co/edit/hqWRG13gzT9H5hxmOIkO?p=preview

    HTML

    <section class="content row" ng-repeat="item in data">
        Name: {{item.name}} <br/>
        BaseValue: <input type="text" ng-init="item.oldBaseValue = item.baseValue" ng-model="item.baseValue" ng-change="baseValueChange(item.oldBaseValue, item.baseValue); item.oldBaseValue = item.baseValue"/>
    </section>
    

    Controller

    $scope.baseValueChange = function(oldVal, newVal) {
        console.log("base value change", oldVal, newVal);
    }
    
    0 讨论(0)
  • 2021-02-06 21:23

    I solved with this solution:

    $scope.updateFields= function(){
        angular.forEach($scope.fields,function (value, key) {
            value.title = value.title.toLowerCase().replace(/\s+/g,'');
        })
    };
    $scope.$watch('fields', $scope.updateFields, true);
    
    0 讨论(0)
  • In this kind of scenario there is no way to circumvent utilizing multiple watches, another way to do this is by utilizing $watchCollection to watch the array of object values, you can get this array using the Object.values function.

    scope.$watchCollection(function() {
        return Object.values(obj);
    }, function(newValues, oldValues) {
        // now you are watching all the values for changes!
        // if you want to fire a callback with the object as an argument:
        if (angular.isFunction(scope.callback())) {
            scope.callback()(obj);
        }
    });
    
    0 讨论(0)
提交回复
热议问题