Add method to Angular directive?

I am trying to create a directive that will improve an HTML element. Therefore, I managed to get a directive to run and associate it with an element. My current code looks something like this:

angular.module('myModule', []) .directive('myDirective', function() { return { restrict: 'C', replace: false, scope: {}, link: function(scope, element, attrs) { } } }); 

Now I would like to add new methods to the HTML element, for example, I would like to do this:

 // Pseudo code myElement.reset(); myElement.reload(); // etc. 

What would be the best way to add these methods to the directive?

+4
source share
2 answers

Adding new methods to elements is not an Angular way. An Angular path would create an object with fields, passing it to a directive and watching for changes inside the directive. Here is a simple example: http://plnkr.co/edit/5v5mN69Bu18jpnoGwYqj?p=preview

+5
source

Your example of your directive is very simple, so I don’t see what you want to achieve. At least I can say: you can define new functions as scope functions, for example.

 ... link: function(scope, element, attrs) { scope.reset = function() { // reset something } // ... } 

If you want to access the downloaded data (for example, for use in the reload () function) in a scope, you must write a controller for this use. therefore, you can enter the service as a data source. Embedding functions directly related to elements is more likely a jQuery way to make it non-angular. In angularjs, you work mainly with areas.

You might provide a more complete example at best with jsfiddle or plnkr, I think it’s easier for you to help see your use case or your problem as part of the working code.

+1
source

All Articles