You can pass arguments to your custom directive, as with the built-in Angular-directives by specifying an attribute in the directive:
angular.element(document.getElementById('wrapper')) .append('<directive-name title="title2"></directive-name>');
What you need to do is define the scope (including argument (s) / parameter (s)) in the factory function of your directive. In the example below, the directive takes a title parameter. Then you can use it, for example, in template , using the usual Angular -way: {{title}}
app.directive('directiveName', function(){ return { restrict:'E', scope: { title: '@' }, template:'<div class="title"><h2>{{title}}</h2></div>' }; });
Depending on how / what you want to link, you have different options:
= - two-way binding@ just reads the value (one way binding)& used to bind functions
In some cases, you may need to use an “external” name that is different from the “internal” name. With external, I mean the name of the attribute in the directory element, and with internal, I mean the name of the variable that is used within the scope.
For example, if we look at the directive above, you can omit another optional attribute for the name, even if you internally want to work with title -property. Instead, you want to use your directive as follows:
<directive-name="title2"></directive-name>
This can be achieved by specifying the name behind the above parameter in the scope definition:
scope: { title: '@directiveName' }
Also pay attention to the following things:
- The HTML5 specification says that user attributes (which is basically what is found everywhere in Angular applications) should have the
data- prefix. Angular supports this by removing data- -prefix from any attributes. Thus, in the above example, you can specify the attribute of the element ( data-title="title2" ) and internally everything will be the same. - The attributes of the elements are always in the form
<div data-my-attribute="..." /> , while in the code (for example, the properties of the area object) they are in the form myAttribute . I lost a lot of time before I realized this. - For a different approach to sharing / sharing data between various Angular components (controllers, directives), you might want to take a look at services or directory controllers.
- Additional information on the Angular homepage (directives)
PzYon Oct. 16 '14 at 16:51 2014-10-16 16:51
source share