I have this code snippet:
<ul>
<li ng-repeat="message in messages">
<button ng-click="send()">Send</button>
</li>
</ul>
$scope.send = function(){
// not working (message undefined)
alert($scope.message.text);
// working
alert($scope.messages[0].text);
};
I do not understand why:
alert($scope.message.text);
does not work. I thought that ng-repeat was creating a new scope.
Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
Use [] if you want an array a.k.a. a list of objects. Use {} if you want to create a single object.
Definition and Usage The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
Its true that ng-repeat
creates a new scope. But you cannot access that scope by doing $scope inside your controller. Instead you can do as below:
<button ng-click="send(message)">Send</button>
And in your JS:
$scope.send = function(message){
alert(message.text);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With