Performance-Custom Directive Vs Plain JQuery selector
by ramandv
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="ControllerA">
<div >
<span ng-repeat="i in list" id='{{i}}' evalue='{{i}}' is-highlighted>
{{i}},
</span>
</div>
</div>
<hr/>
<div ng-controller="ControllerB">
<div >
<span ng-repeat="i in list" id='b{{i}}' ng-mouseover='onMouseover(i)'>
{{i}},
</span>
</div>
</div>
</div>
CSS
.highlight {
background-color :#CCC;
}
JavaScript
angular.module('myApp', [])
.service('myService', function ($rootScope) {
var _list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100
];
var _highlightedElement = 0;
return {
getList : function() {
return _list;
},
getHightlightedElement : function() {
return _highlightedElement;
},
setHightlightedElement : function(i) {
_highlightedElement = i;
}
};
})
.directive('isHighlighted', ['myService', function() {
return {
restrict: 'A',
controller : function($scope, $attrs, myService) {
$scope.myService = myService
},
link: function($scope, element, attrs, controller) {
$scope.$watch('myService.getHightlightedElement()', function(n, o) {
if(attrs.evalue == n) {
element.addClass("highlight");
}
else {
element.removeClass("highlight");
}
});
}
};
}]);
function ControllerA($scope, myService) {
$scope.list = myService.getList();
}
function ControllerB($scope, myService) {
$scope.list = myService.getList();
$scope.onMouseover = function (i) {
console.log(i);
myService.setHightlightedElement(i);
}
}