[英]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.