Angular directives
Demonstrate angularJS directive
by de Montalembert Jonathan
HTML
<div ng-controller="MainCtrl">
<div magic="" magic-color="red" magic-click="clickHandler">
world
</div>
</div>
<script type="text/ng-template" id="templates/magic.html">
<div> hello <span ng-transclude> </span>
</div>
</script>
CSS
.red {
color:red;
}
.green {
color:green;
}
JavaScript
var app = angular.module('app', []);
app.controller("MainCtrl", function ($scope) {
$scope.clickHandler = function(elem){
elem.toggleClass('red').toggleClass('green');
};
});
app.directive('magic', function ($rootScope) {
return {
restrict: 'A', // use as attribute
templateUrl: 'templates/magic.html',
transclude: true,
replace: true,
scope: {
magicClick: '='
},
link: function (scope, element, attr) {
element.addClass(attr.magicColor);
if (attr.magicClick) {
element.bind('click', function(){
scope.$apply(scope.magicClick(element, attr));
})
}
}
}
});
angular.bootstrap(document.body, ['app']);