user2598794
user2598794

Reputation: 727

How to pass an argument to 'ng-click' handler in angularjs directive programmatically

In my directive I want to add a 'ng-click' attribute to an icon with handler which accepts an id like this:

icon.attr('ng-click', 'iconclick(' + node.id + ')');

But I get an error:

Error: [$parse:syntax] http://errors.angularjs.org/1.4.3/$parse/syntax?p0=cca11656e285b0566ffde2&p1=is%20unexpected%2C%20expecting%20%5B)%5D&p2=13&p3=iconclick(55cca11656e285b0566ffde2)&p4=cca11656e285b0566ffde2)
    at Error (native)
    at http://localhost:3010/javascripts/vendor/angular.min.js:6:416
    at Object.q.throwError (http://localhost:3010/javascripts/vendor/angular.min.js:209:32)
    at Object.q.consume (http://localhost:3010/javascripts/vendor/angular.min.js:209:207)
    at Object.q.primary (http://localhost:3010/javascripts/vendor/angular.min.js:206:181)
    at Object.q.unary (http://localhost:3010/javascripts/vendor/angular.min.js:205:174)
    at Object.q.multiplicative (http://localhost:3010/javascripts/vendor/angular.min.js:204:434)
    at Object.q.additive (http://localhost:3010/javascripts/vendor/angular.min.js:204:261)
    at Object.q.relational (http://localhost:3010/javascripts/vendor/angular.min.js:204:96)
    at Object.q.equality (http://localhost:3010/javascripts/vendor/angular.min.js:203:425) <span ng-click="iconclick(55cca11656e285b0566ffde2)">

What is wrong here? I tried also string.concat but with the same result.

Upvotes: 0

Views: 283

Answers (3)

Fissio
Fissio

Reputation: 3758

Try icon.attr('ng-click', 'iconclick("' + node.id + '")');

I'm assuming your id to be a string, you'll need to add quotes around the argument for your function to recognize it a string.

Upvotes: 0

valverde93
valverde93

Reputation: 1698

You can add an event by using on() of JQLite

Here the documentation

Upvotes: 0

deceze
deceze

Reputation: 522015

Instead of adding more meta directives, you should probably rather write the directive along these lines:

.directive('foo', function () {
    return function (scope, element) {
        element.on('click', scope.iconclick.bind(null, element[0].id));
    };
})

In other words, you have direct access to the scope object and its attached functions and can trigger them directly. ng-click is just a helper to do this declaratively in a template, you don't need to use it to call a function on the scope.

Upvotes: 1

Related Questions