Adding parameter to ng

I have a simple loop with ng-repeat like this:

<li ng-repeat='task in tasks'>
  <p> {{task.name}}
  <button ng-click="removeTask({{task.id}})">remove</button>
</li>

There is a function in the controller $scope.removeTask(taskID) .

As far as I know Angular will first render the view and replace interpolated {{task.id}} with a number, and then, on click event, will evaluate ng-click string.

In this case ng-click gets totally what is expected, ie: ng-click="removeTask(5)". However... it's not doing anything.

Of course I can write a code to get task.id from the $tasks array or even the DOM, but this does not seem like the Angular way.

So, how can one add dynamic content to ng-click directive inside a ng-repeat loop?


Instead of

<button ng-click="removeTask({{task.id}})">remove</button>

do this:

<button ng-click="removeTask(task.id)">remove</button>

Please see this fiddle:

http://jsfiddle.net/JSWorld/Hp4W7/34/


One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:

<button ng-click="removeTask(1234)">remove</button>

I saw:

<button ng-click="removeTask(task.id)">remove</button>

However, the latter works!

This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.

Further, if you wanted to pass the task object itself, you can like:

<button ng-click="removeTask(task)">remove</button>

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click . The parameter passed to goTo() is a string from a property of the binding object (the button ), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

链接地址: http://www.djcxy.com/p/77912.html

上一篇: 带默认选项的Angular指令

下一篇: 将参数添加到ng