Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
57
rated 0 times [  59] [ 2]  / answers: 1 / hits: 61708  / 10 Years ago, tue, july 22, 2014, 12:00:00

I have this data in my controller



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


with some html like this:



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


Now, I want to know when the baseValue is changed but because of I using a objects inside the data variable I can not watch the property in a simpler way.



I have tried something like this, but I have to loop all the array



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


How can I do a simpler $watch to know only when the baseValue is changed?



Similar questions:





UPDATE 1



I could add an individual watch for each object to know when the baseValue is changed, but it won't be nice if I had an n number of objects, not only a couple of objects like in this example



$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`

More From » angularjs

 Answers
14

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

[#70109] Saturday, July 19, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lidialyrick

Total Points: 737
Total Questions: 104
Total Answers: 89

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
lidialyrick questions
;