jviotti jviotti - 1 year ago 106
AngularJS Question

Pass a reference to DOM object with ng-click

I have multiple elements with the same callback on ng-click:

<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>
<button ng-click="doSomething()"></button>

// In controller:
$scope.doSomething = function() {
// How do I get a reference to the button that triggered the function?

How can I get the reference to the object which made the call to doSomething? (I need to remove an attr from it)

Answer Source

The angular way is shown in the angular docs :)


Here is the example they use:

    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download