1

I'm wondering is a way to add an ng-click as an attribute?

Let's say I want to add ng-click if my <li> has a class someClass:

angular.element(root.querySelector('li.someClass').attr({'ng-click': 'someFunc()'});

And when <li> has a class anotherClass I want to reset the ng-click:

angular.element(root.querySelector('li.someClass').attr({'ng-click': ''});

But it didn't work.

I can't make it in my HTML:

<li class="someClass" ng-click="someFunc()"> ... </li>
<li class="anotherClass"> ... </li>

because my HTML is generated dynamically by ng-repeat and also there is a directive which make some mess with ng-hide.

The best solution will be with the angular.element but ng-click isn't an attribute right?

(I can debug the code in Visual Studio and when I add ng-click in a way <li ng-click="someFunc()">...</li> I can't find it in the Locals Window in VS)

1
  • ng-click isn't a "real" attribute. It is an angular directive. Adding it via angular.element or jquery will not make angular run it. Could you give your ng-repeat and what is wrong with it ? We could fix that instead of trying to do some things in a non-angular way :). Commented Aug 5, 2015 at 13:01

3 Answers 3

1

Check the class name in handler function instead reset ng-click

JS

$scope.someFunc = function (e) {

    if(angular.element(e.target).hasClass("someClass")){
        //code goes here
    };
}

HTML

<li class="someClass" ng-click="clickHandler($event)">Button</li>
Sign up to request clarification or add additional context in comments.

Comments

0

You can't really toggle ng-click since it's a angular directive but you can add conditions like so:

<li ng-click="someVar === true ? callOnMe() : ''">CLICK ME</li>

Demo fiddle: http://jsfiddle.net/gnrL6cLw/

Note: Change $scope.someVar to be true to see the alert.

Comments

0

Without seeing your ng-repeat code, it's hard to say - but, if I'm understanding your goal correctly, I think you could use ng-switch with ng-switch-when to achieve the output you want:

<ul ng-repeat="item in items" ng-switch="item.someCondition">
    <li ng-switch-when="true" class="someClass" ng-click="someFunc()">...</li>
    <li ng-switch-when="false" class="anotherClass">...</li>
</ul>

That way it should render the list item you want to display based upon the condition. Of course, item.someCondition doesn't have to be a boolean value - you could match on a string, int, or any other type you like.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.