В моей директиве у меня есть пользовательские шаблоны и замена существующим. когда пользовательские шаблоны кликают, мне нужно обновить $scope.index
для обновления.
но он не работает. но когда я консолю свойство, все работает. Каков правильный способ сделать это?
вот моя специальная директива:
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());
}
}
})
В html изменить строку
<new-array index='$index' update="update" value='value' ng-repeat="value in values">{{value.name}}</new-array>
в
<new-array index='$index' update="update($index)" value='value' ng-repeat="value in values">{{value.name}}</new-array>
В js change:
scope.update(scope.value.num);
в
scope.update({num: scope.value.num});
и, наконец, изменить:
$scope.update = function (num) {
$scope.index = num;
}
в
$scope.update = function (num) {
$scope.index = num;
$scope.$apply();
}