programing

AngularJS는 객체 배열 내의 객체 속성을 감시합니다.

css3 2023. 3. 21. 22:26

AngularJS는 객체 배열 내의 객체 속성을 감시합니다.

나는 이것을 가지고 있다.data컨트롤러로

    $scope.data = {
        home: {
            baseValue: "1",
            name: "home"
        },
        contact: {
            baseValue: "2",
            name: "contract"
        }
     // a lot more options
    };

다음과 같은 html을 사용합니다.

<section class="content row" ng-repeat="item in data">
   {{item.name}}
   ....
</section>

이제, 나는 언제가 될지 알고 싶다.baseValue변경되었지만 데이터 변수 내의 개체를 사용하기 때문에 변경할 수 없습니다.watch좀 더 간단한 방법으로요.

이와 같은 시도를 해봤지만 모든 어레이를 루프해야 합니다.

$scope.$watch('data', function (newValue, oldValue, scope) {
 // some code to compare the tow arrays, line by line
}, true);

어떻게 하면 더 심플하게$watch알 수 있는 것은baseValue변경되었습니까?

유사한 질문:

업데이트 1

각 오브젝트에 대해 개별 워치를 추가하여 언제 해당 워치를 사용할 수 있는지 알 수 있습니다.baseValue바뀌긴 했지만, 만약 내가 이 모든 것을 가졌다면n개체 수, 이 예시와 같은 개체 몇 개뿐 아니라

$scope.$watch('data.home', function (newValue, oldValue, scope) {
 // do some stuff with newvalue.baseValue
}, true);

$scope.$watch('data.contact', function (newValue, oldValue, scope) {
 // do some stuff with newvalue.baseValue
}, true);
... // Adds more individual `watch`

질문에 따라 ngChange를 사용하여 변경 내용을 확인할 수 있습니다.baseValue기능을 트리거합니다.

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>

컨트롤러

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

oldValue와 newValue를 얻을 수 있는 보다 고도의 버전은 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>

컨트롤러

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

오브젝트 속성을 감시할 수 있습니다.
그래서 이런 걸 할 수 있어요

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

테스트는 안 했지만 아이디어는 간단해

이러한 시나리오에서는 여러 개의 시계를 사용하는 것을 피할 수 없습니다.또 다른 방법은$watchCollection오브젝트 값의 배열을 감시하려면 , 다음의 방법으로 이 배열을 취득할 수 있습니다.Object.values기능.

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);
    }
});

이 솔루션으로 해결했습니다.

$scope.updateFields= function(){
    angular.forEach($scope.fields,function (value, key) {
        value.title = value.title.toLowerCase().replace(/\s+/g,'');
    })
};
$scope.$watch('fields', $scope.updateFields, true);

언급URL : https://stackoverflow.com/questions/24876944/angularjs-watch-an-object-property-in-an-object-array