Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add method to Angular directive?

I'm trying to create a directive that would enhance an HTML element. So I managed to get the directive to run and to be associated with the element My current code is 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?

like image 977
laurent Avatar asked Apr 16 '13 06:04

laurent


2 Answers

Adding new methods to elements is not the Angular way. The angular way would be creating object with fields, passing it to directive and watch for field changes inside directive. Here is simple example: http://plnkr.co/edit/5v5mN69Bu18jpnoGwYqj?p=preview

like image 188
Artem Avatar answered Sep 18 '22 16:09

Artem


Your example of your directive is very basic, so I can't see what do you want to achieve. At least I can say: You can define new functions as functions of the scope , e.g.

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

If you want to access data loaded (e.g. for use in function reload()) in the scope you should write a controller for this use. so you can inject a service as a data source. Implementing functions bound to elements directly is more the jQuery way to do not the angularjs one. In angularjs you work with scopes mainly.

Maybe you provide a more complete example at best using jsfiddle or plnkr, I think it easier to help to see your use case or your problem as a piece of working code.

like image 24
Lutz Avatar answered Sep 19 '22 16:09

Lutz