Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Scope is not what expected inside an ng-click event of ng-repeat

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.

like image 806
poiuytrez Avatar asked Aug 14 '13 09:08

poiuytrez


People also ask

Does ng-repeat create a new scope?

Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.

What is[] in AngularJS?

Use [] if you want an array a.k.a. a list of objects. Use {} if you want to create a single object.

What is ng-repeat?

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.

What is the difference between Ng-click and Onclick?

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.


1 Answers

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);    
};
like image 146
AlwaysALearner Avatar answered Oct 14 '22 03:10

AlwaysALearner