问题
Is possible to reach variable outside the ng-repeat scope?
jsfiddle: http://jsfiddle.net/zcbhubrw/
Here is the code:
HTML
<div class="section" ng-app="phonecatApp" ng-controller="PhoneListCtrl">
<div class="slide" >
<div class="container">
<h2 class="section-title">Selected Mobiles</h2>
</div>
<div class="container-fluid fix ver2">
<div class="col-md-3 work-thumb" ng-repeat="phone in phones">
<a href="#" ng-click="count = {{$index}}">
{{phone.name}}
</a>
</div>
</div>
</div>
<p>Count: {{count}}</p>
</div>
Controller
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', function ($scope) {
$scope.phones = [
{'name': 'Nexus S',
'snippet': 'Fast just got faster with Nexus S.'},
{'name': 'Motorola XOOM™ with Wi-Fi',
'snippet': 'The Next, Next Generation tablet.'},
{'name': 'MOTOROLA XOOM™',
'snippet': 'The Next, Next Generation tablet.'}
];
});
I need to reach the {{count}} variable for further usage.
回答1:
you can call a function while clicking the list inside ng-repeat
like this
<a href="#" ng-click="setCount($index)">
and defining the function in controller
$scope.setCount = function(index) {
$scope.count = index;
} ;
and updating the count value when you click
Here is a working plunker with your code,
http://embed.plnkr.co/rAbanmAR2Chw3P501tDc/preview
Hope this helps!
回答2:
You can create function in the controller to set the count or refer the parent scope from inside the ng-repeat
ng-click="$parent.count = $index"
using parent scope
using function
来源:https://stackoverflow.com/questions/30288248/how-to-reach-variable-outside-the-ng-repeat-scope