Reputation: 202
I created one directive and I'm looping it. The problem I'm having is that for some reason the $scope.name shows the name from the last directive even though I did an isolate scopes
angular.module("testApp")
.controller("testingCtrl","$scope",function($scope) {
infos =[
{
name ="test1"
},
{
name ="test2"
}
]
$scope.init=function(name){
$scope.name=name
}
})
.controller("directiveCtrl",["$scope",function($scope){
console.log("HEY",$scope.name);
}])
.directive("testing",function(){
return{
restrict:"E",
controller:"directiveCtrl",
scope:{
name:"="
},
template:"<h1>{{name}}</h1>"
}
})
<div ng-app="testApp">
<div ng-controller="testingCtrl">
<div ng-repeat="info in infos" ng-init="init(info.name)">
<testing name="name"></testing>
</div>
</div>
</div>
so it's showing
test2
test2
but what I want is
test1
test2
Thank you for your time.
Upvotes: 1
Views: 51
Reputation: 81
I'm not sure why yours was having those issues, but when trying to replicate your problem I made a codepen with the following changes as I assume you didn't copy your working Angular code exactly:
ng-repeat
to info in infos
(yours wasn't working)info.name
to the directive instead of {name:info.name}
These changes caused it to output
test1
test2
Here's my codepen: http://codepen.io/anon/pen/JRKyAK?editors=1010#0
Edit:
With the edits you've made, you have a different problem.
The reason you are seeing test2
repeated, is because you are calling init(info.name)
in your ng-init
for each info
in infos
, as that init function is invoked each time Angular generates one of those new divs.
The problem with that, is that $scope.init
is overwriting $scope.name
every time ng-repeat
generates a new info div. This is what is causing your last element to always be displayed, as your directive is being passed $scope.name
which will always contain your last element's name.
I'd suggest not using ng-init
, and rather pass info attributes such as name directly into your directive like so:
<testing name="info.name"></testing>
Upvotes: 3