Today I’m gonna explain Directives a little bit here. I’d like to think of Directives as a function that we run on a particular DOM element. ain’t cool to have provide extra functionality on an element. For example, the ng-click directive gives an element (could be a button, link or anything else) the ability to listen for the click event and run an Angular method when it receives the event. Directives are what makes the Angular framework so powerful, and, as you might already know, we do get to create custom ones as well. here is an example of a custom directive where I’ve created several HTML wrapper and a custom directive. the directive is introduced in form of an attribute of a <div> tag. take a look at the results and you’d understand how it works, easy :).
<!doctype html> <html ng-app="myApp"> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script> </head> <body> <div ng-app="myApp" ng-init=" someProperty= 'some data'"></div> <div ng-init="siblingProperty= 'more data'"> Inside Div Two: {{ myFirstProperty }} <div ng-init="myFirstProperty = 'data for 3rd property'" ng-controller="MyFirstCtrl"> Inside Div Three: {{ myFirstProperty }} <div ng-controller="MyCtrl"> Inside Div Four: {{ myFirstProperty }} <br> Outside myDirective: {{ myProperty }} <div my-directive ng-init="myProperty = 'data inside property'"> Inside myDirective: {{ myProperty }} <div> </div> </div> </div> <script src="app.js"><script> </body> </html>
and in your app.js file:
angular.module('myApp', []) .controller('MyFirstCtrl', function($scope) { // we can leave it empty, it just needs to be defined }) .controller('MyCtrl', function($scope) { // lets leave it empty }) .directive('myDirective', function() { return { restrict: 'A', scope: true } })
Comments 0