How do you pass data to your directive?
So now we have covered the most basic part of custom directives, and now you should learn how to pass data to it.
You can simple access the current scope from a controller and get the data this way.
JavaScript:
angular.module('app', []) .controller('HelloWorldController', ['$scope',function($scope) { $scope.message = "This is a wonderful world we live in!" }]) .directive('helloWorld', function () { return { restrict: 'E', templateUrl: 'template.html' }; });
Html Code:
<body ng-controller="HelloWorldController"> <hello-world></hello-world> </body>
Template:
Your message: <b>{{message}}</b>
And then in your template you simply use the curly braces to display the message from the current scope.
But if you are planning to reuse this directive this approach can cause a lot of problems later. So best practice is to use isolated scope within the directive. To isolate the scope we need to define the scope property inside the configuration object of your directive.
angular.module('app', []) .directive('helloWorld', function () { return { restrict: 'E', scope : { message: '@' }, templateUrl: 'template.html' }; });
Inside the scope property I have specified a message attribute as string by using ‘@’ symbol. If you are passing data model or value that is not text you can use the ‘=’ symbol. If you want the attribute name to be different to the scope name you can do this too.
scope: { personDetail: '=person' }
In your html code you would pass a model to the person attribute.
<person-detail-view person="person"></person-detail-view>
- ‘@’ – Text attribute.
- ‘=’ – Make attribute name the same as the scope name.
- ‘=attributeName’ = Give an attribute it’s own name.
- ‘=?’ – This is an optional attribute.
If you would like to obtain a copy of the sample code for this post, you can download them from GitHub.
https://github.com/csharpguy76/LearnAngularJS