[英]Angularjs directive call controller function
我有一個指令,使一個長長的清單。 渲染工作的非常好和快速,現在我想在帶參數的Controller上調用一個函數。 我怎樣才能做到這一點?
這是我的指令:
.directive("slheats", function () {
return {
restrict: "A",
scope: {
slheats: "=",
},
link: function (scope, element, attrs) {
scope.$watch("slheats", function (data) {
angular.forEach(data, function (heat, h) {
var body = "";
var first = true;
var ct = 1;
body += "<div class='row heat'>" + heat.Heat + "</div>";
angular.forEach(heat.Entries, function (entry, e) {
var line = "";
ct++;
line += "<div class='name'><button ng-click='showdetails()'>" + entry.Name + "</button></div>";
body += line;
});
$(element).append(body);
});
});
}
}
})
.controller('startlistcontroller',['$scope', 'apiservice', 'objectservice', function ($scope, apiservice, objectservice) {
$scope.startlists = [];
$scope.selected = null;
$scope.showdetails = function (x) {
alert(x);
};
如何在控制器上調用showdetails函數?
謝謝曼紐爾!
假設您要引用的控制器具有指令的父范圍,則需要使用angular的Scope Function Expression Binding綁定函數 。 請參閱此處的 #8。 因此可能看起來像:
.directive("slheats", function () {
return {
...
scope: {
slheats: "=",
internalShowdetails: "&"
},
link: function (scope, element, attrs) {
....
line += "<div class='name'><button ng-click='internalShowdetails()'>" + entry.Name + "</button></div>";
....
}
});
然后在您的html中:
<div slheats="something" internal-show-details="showdetails(a, b, c)"></div>
附加參考: http : //onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
更新:
因此,如果您在指令上使用template(Url)
屬性,則上述方法將按預期工作,但是如果在OP進行link
函數內呈現html時,則需要先使用$compile
。 這是顯示其工作原理的plnkr 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.