1

Is there a simple declarative way (without a additional function in the $scope) to marked clicked element with AngularJS?

e.g. I have a button which I want to marked as clicked/checked.

<button ng-model="form.btn" ng-click=" // do stuff here to add a class or attr ">Go</button>

I was able to achieve this with external function but I am looking for a declarative way / all in HTML template.

4 Answers 4

4

If you want toggle class use this: http://jsbin.com/vimero/1/edit

<button ng-model="btn" ng-click="btn =! btn" ng-class="{'active' : btn}"> 
 Toogle 
</button>
Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain what is going on here? This btn =! btn looks very mysterious .
@User789 it change from true to false and false to true. It's a toggle. But it should be btn = !btn;
1
<button ng-model="form.btn" ng-click="form.btn = true" 
ng-class="{'active' : form.btn}">
    Go
</button>

2 Comments

That assumes that form.btn will be bool value, string will fail here, please extend it to be more generic ;)
Yes - string would be very useful, would be great to have this inside a ng-repeat with an array like ['yes', 'no']
1

ng-click="yourFunction($event.target)"

And do your transformations in yourFunction. You'll have HTMLElement passed as 1st param.

Comments

1

I found this works pretty well for a group of buttons to toggle active ng-class if the condition set in ng-click is met:

<button ng-class="{'active' : activeButton == 'firstButton'} ng-click="activeButton = 'firstButton'>
  First Button
</button>
<button ng-class="{'active' : activeButton == 'secondButton'} ng-click="activeButton = 'secondButton'>
  Second Button
</button>
<button ng-class="{'active' : activeButton == 'thirdButton'} ng-click="activeButton = 'thirdButton'>
  Third Button
</button>

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.