Angular $watch :- To get clear understanding on $watch below i have implemented the example using $watch and without using it. In one liner definitions we can watch on variables based on changes to it we can correspondingly change the variables dependent on it in angular scope. Something like observer pattern but exactly not like that
Example :- In this example we will have a text box and a label beside to display computed fund based on initial fund release.
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script >
var angModule = angular.module("app",[]);
angModule.controller("checkWatchProperty",function($scope){
$scope.funding = {startingEstimate:0}
//without watch
$scope.computeNeeded = function(){
$scope.funding.needed = $scope.funding.startingEstimate*10;
}
//with watch
$scope.$watch('funding.startingEstimate', function(){
$scope.funding.needed = $scope.funding.startingEstimate*10;
});
});
</script>
</head>
<body ng-controller="checkWatchProperty">
<!--With out watch -->
Starting : <input ng-model="funding.startingEstimate" ng-change="computeNeeded()">
<!--With watch we no need to attach the ng-change as previous statement. Angular takes care of invoking callback function-->
Starting : <input ng-model="funding.startingEstimate" >
Recommendation : {{funding.needed}}
</body>
</html>
Example :- In this example we will have a text box and a label beside to display computed fund based on initial fund release.
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script >
var angModule = angular.module("app",[]);
angModule.controller("checkWatchProperty",function($scope){
$scope.funding = {startingEstimate:0}
//without watch
$scope.computeNeeded = function(){
$scope.funding.needed = $scope.funding.startingEstimate*10;
}
//with watch
$scope.$watch('funding.startingEstimate', function(){
$scope.funding.needed = $scope.funding.startingEstimate*10;
});
});
</script>
</head>
<body ng-controller="checkWatchProperty">
<!--With out watch -->
Starting : <input ng-model="funding.startingEstimate" ng-change="computeNeeded()">
<!--With watch we no need to attach the ng-change as previous statement. Angular takes care of invoking callback function-->
Starting : <input ng-model="funding.startingEstimate" >
Recommendation : {{funding.needed}}
</body>
</html>
No comments:
Post a Comment