Reputation: 4917
I'm trying to get information about performance in an AngularJS application. I wonder if there is any performance difference between using $watch
or ng-if
, as we can use one or the other to obtain the same result/behavior.
Note that I'm using $watch
only to check if the data is loaded. The directive doesn't need to watch for future data changes
As an example let's say we have a controller that retrieves data from an Ajax request and a directive that needs this data.
$watch
The controller
angular.module('myApp').controller(
'MyController',
['$scope', 'MyService',
function ($scope , MyService) {
$scope.myObj = {}
// http request
MyService.getData( function (result) {
$scope.myObj.myData = result
})
}
]
);
The directive
angular.module('app').directive(
'myCustomDirective',
[ function () {
return {
restrict: 'E',
scope : {
data : '=' // the data provided by the MyController
},
link: function (scope, element, attrs) {
// watching changes on data
var myWatcher = $scope.$watch(data, function(value) {
if(value) {
// do something with data
myWatcher(); //kill watcher
}
});
},
templateUrl: '/myTemplate.html'
};
}]);
HTML file
<div ng-controller="myController">
<div>
<my-custom-directive data="myObj.myData"></my-custom-directive>
</div>
</div>
ng-if
The controller (no changes)
angular.module('myApp').controller(
'MyController',
['$scope', 'MyService',
function ($scope , MyService) {
$scope.myObj.myData = {}
// http request
MyService.getData( function (result) {
$scope.myObj.myData = result
})
}
]
);
The directive (removing $watch)
angular.module('app').directive(
'myCustomDirective',
[ function () {
return {
restrict: 'E',
scope : {
data : '='
},
link: function (scope, element, attrs) {
// do something width data
},
templateUrl: '/myTemplate.html'
};
}]);
HTML file (adding ng-if
directive)
<div ng-controller="myController">
<div ng-if="myObj.myData">
<my-custom-directive data="myObj.myData"></my-custom-directive>
</div>
</div>
So my questions are:
Any advice is very appreciated.
Upvotes: 1
Views: 1013
Reputation: 9476
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) ....
So ng-if uses $watch, most angular directives does. So there is no real difference.
But there is no sense in creating directive that does something already implememnted. So in general it is better to use angular built-in directives, if you need something new - do not afraid to use $watch.
Upvotes: 1