Шаблон директивы (items.html)
<li ng-repeat="item in itemCart">
{{item.title}} <br>
{{item.category}}  
{{ formatCurrencyFunction({cost: item.price}) }}
</li>
Эта настраиваемая директива используется в Second.html
<h1>
This is Second.
{{header}}
</h1>
<hr>
<ul>
<items-list item-cart="items" format-currency-function="formatPrice(cost)"></items-list>
</ul>
Код для контроллера:
myApp.directive("itemsList", function(){
return{
templateUrl:"contents/Views/Directives/Items.html",
replace: true,
scope:{
itemCart: "=",
formatCurrencyFunction: "&"
},
restrict:"EACM" // E-Element A-Attribute C-Class M-Comments
}
})
myApp.controller('secondController', ['$scope', '$log', '$http','$routeParams', function($scope, $log, $http, $routeParams) {
$scope.formatPrice = function(price){
return "₹ "+parseFloat(price).toFixed(2);
};
$scope.header = 'Second ' + ($routeParams.num || "");
$scope.testSecond = "Second";
$http.get("/items")
.success(function(data){
$scope.items = data;
});
}]);
Функция formatPrice не вызывается из директивы Items.html
Что нужно исправить в моем коде, чтобы заставить его работать?
Функция контроллера 'formatCurrencyFunction()' не может быть вызвана, просто поместив ее в выражение.
Чтобы использовать функцию, которую нужно вызвать на основе четного, в вашем случае ng-init будет работать.
<li ng-repeat="item in itemCart" ng-init="formatCurrencyFunction({cost: item.price})">
{{item.title}} <br>
{{item.category}}
</li>
Получил эту работу, используя ng-repeat на странице Second.html вместо директивы.
Шаблон директивы (items.html)
<li>
{{item.title}} <br>
{{item.category}}  
{{ formatCurrencyFunction({cost: item.price}) }}
</li>
Эта настраиваемая директива используется в Second.html
<h1>
This is Second.
{{header}}
</h1>
<hr>
<ul>
<items-list item="item" format-currency-function="formatPrice(cost)" ng-repeat="item in items"></items-list>
</ul>
Код в файле JS
myApp.directive("itemsList", function(){
return{
templateUrl:"contents/Views/Directives/Items.html",
replace: true,
scope:{
item: "=",
formatCurrencyFunction: "&"
},
restrict:"EACM" // E-Element A-Attribute C-Class M-Comments
}
})
Внутри функции директивной ссылки вам нужно вызвать метод, применив какое-то событие к этому атрибуту
Внутри функции директивной ссылки вы хотите вызвать метод следующим образом:
scope.someFn({arg: someValue});
myApp.directive("itemsList", function(){
return{
templateUrl:"contents/Views/Directives/Items.html",
replace: true,
scope:{
itemCart: "=",
formatCurrencyFunction: "&formatCurrencyFunction"
},
link:function(scope, element, attrs){
scope.formatPrice({arg: 35}); //scope.someFn({arg: 35});
},
restrict:"EACM" // E-Element A-Attribute C-Class M-Comments
}
})