Reputation: 15303
In my directive, i have custom templates and replacing with existing one. when the custom templates click, i need to update the $scope.index
to update.
but it's not working. but when i console the property it all works. what is the correct way to do this?
here is my custom directive:
var myApp = angular.module('myApp', []);
myApp.controller('main', function ($scope) {
$scope.values = [{"name":"one", "num" : 1}, {"name":"two", "num" : 2}, {"name":"three", "num" : 3}]
$scope.index = 0;
$scope.update = function (num) {
$scope.index = num;
}
});
myApp.directive("newArray", function ($compile) {
return {
scope : {
value : "=",
index : "=",
update:"&"
},
link : function (scope, element, attrs) {
var getTemplate = function (val, index) {
switch(index) {
case 0 :
return $('<div />', {
class:'red',
html : "<h1>testing</h1>",
click : function () {
console.log(scope.value.num); //works
scope.update(scope.value.num); //not wroking
}
});
break;
case 1 :
return $('<div />', {
class:'blue',
html : "<h1>testing</h1>",
click : function () {
scope.update(scope.value.num);
}
});
break;
case 2 :
return $('<div />', {
class:'green',
html : "<h1>testing</h1>",
click : function () {
scope.update(scope.value.num);
}
});
break;
}
}
element.html(getTemplate(scope.value, scope.index));
$compile(element.contents())(scope);
element.replaceWith(element.contents());
}
}
})
Upvotes: 0
Views: 356
Reputation: 4483
In the html change the line
<new-array index='$index' update="update" value='value' ng-repeat="value in values">{{value.name}}</new-array>
to
<new-array index='$index' update="update($index)" value='value' ng-repeat="value in values">{{value.name}}</new-array>
In the js change:
scope.update(scope.value.num);
to
scope.update({num: scope.value.num});
and finally change:
$scope.update = function (num) {
$scope.index = num;
}
to
$scope.update = function (num) {
$scope.index = num;
$scope.$apply();
}
See updated plunker
Upvotes: 2