I am trying to update values of variables b
and c
with an add method (simply incrementing their value) but a
(the sum of the two) is not reflecting this operation.
I understand we can use a $scope.$watch
function to update them, but I have an application with many objects dependent on other objects. If my dependent object changes I want my object to also changes without using any $watchers.
This is just a simple example where I am trying to get $scope.a
and $scope.obj.a
value updated with the help of watchers. How do I do this?
<html ng-app="app">
<head>
<title></title>
</head>
<body ng-controller="ctrl">
a : {{a}}<br />
b: {{b}}<br />
c: {{c}}<br />
<button ng-click="add();">Add</button>
<br /><br /><br />
obj.a : {{obj.a}}<br />
obj.b: {{obj.b}}<br />
obj.c: {{obj.c}}<br />
<button ng-click="obj.add();">obj.Add</button>
<script type="text/javascript" src="angular.min.js"></script>
<script>
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
$scope.b = 1;
$scope.c = 2;
$scope.a = $scope.b + $scope.c;
$scope.$watch('b', function (newValue, oldValue) {
$scope.a = $scope.b + $scope.c;
});
$scope.add = function () {
$scope.b++;
$scope.c++;
};
//this is object with dot property example
$scope.obj = {};
$scope.obj.b = 1;
$scope.obj.c = 2;
$scope.obj.a = $scope.obj.b + $scope.obj.c;
$scope.$watch('obj.b', function (newValue, oldValue) {
$scope.obj.a = $scope.obj.b + $scope.obj.c;
});
$scope.obj.add = function () {
$scope.obj.b++;
$scope.obj.c++;
};
});
</script>
</body>
</html>
You can achieve this by declaring a (or obj.a respectively) as a function instead of an object / object property. The function will automatically by re-executed by Angular each time any of the properties it uses change and therefore your "a" values will change without the need for you to explicitly define the watches.
See your updated code below:
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
$scope.b = 1;
$scope.c = 2;
$scope.a = function() {return $scope.b + $scope.c};
$scope.add = function () {
$scope.b++;
$scope.c++;
};
//this is object with dot property example
$scope.obj = {};
$scope.obj.b = 1;
$scope.obj.c = 2;
$scope.obj.a = function() {
return $scope.obj.b + $scope.obj.c;
}
$scope.obj.add = function () {
$scope.obj.b++;
$scope.obj.c++;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="app">
<head>
<title></title>
</head>
<body ng-controller="ctrl">
a : {{a()}}<br />
b: {{b}}<br />
c: {{c}}<br />
<button ng-click="add();">Add</button>
<br /><br /><br />
obj.a : {{obj.a()}}<br />
obj.b: {{obj.b}}<br />
obj.c: {{obj.c}}<br />
<button ng-click="obj.add();">obj.Add</button>
</body>
</html>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다