Scene description:
There is a month select drop-down box on the page. Click the drop-down box and we can select the corresponding month
<select ng-model="month"></select>
In the controller, you need to go to the backend to obtain the corresponding data according to the selected month
$scope.$watch($scope.month, function(){
$http({ url:url,method:'GET',withCredentials:true
}).success(function(data,header,config,status){
// do something
})
});
My thoughts:
Assuming there are multiple drop-down boxes on the page, using $watch to monitor $scope changes one by one is not ideal. Is there any idea that instead of using $watch, when the ng-model changes, the controller automatically sends an http request to obtain the data?
Looking for expert guidance~
曾经蜡笔没有小新2017-05-15 17:08:13
Your $watch is written incorrectly:
你写成了: $scope.$watch($scope.month, ...
应该写成: $scope.$watch('month', ...
The following method is also very simple:
<select ng-model="year"></select>
<select ng-model="month"></select>
<select ng-model="day"></select>
$scope.changeDo = function(){
$http({
url:url,
method:'GET',
withCredentials:true
}).success(function(data,header,config,status){
// do something
});
};
$scope.$watch('year', $scope.changeDo);
$scope.$watch('month', $scope.changeDo);
$scope.$watch('day', $scope.changeDo);
If you use ng-change, the performance may be better. Remember to remove $watch() above:
<select ng-model="year" ng-change="changeDo();"></select>
<select ng-model="month" ng-change="changeDo();"></select>
<select ng-model="day" ng-change="changeDo();"></select>
The performance difference is basically negligible. I have done a similar test before, executed 1 million times, within 1 second.
If I do it, I will use the $watch method, which is convenient for maintenance later (ng-change method requires changing the controller and template, while watch method only needs to change the controller).
大家讲道理2017-05-15 17:08:13
Drop-down boxes are generally processed using the ngChange
command; ngChange
给我你的怀抱2017-05-15 17:08:13
ngChange is the best choice. In principle, set as few listening queues as possible, otherwise the efficiency will be very low.