我有一个指令,它会呈现一个很长的列表。渲染工作非常精细和快速,现在我想在带参数的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函数?
感谢曼努埃尔!
答案 0 :(得分:3)
假设您引用的控制器具有指令的父范围,您需要使用角度范围函数表达式绑定绑定该函数。见#8 here。所以它可能看起来像:
.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,则需要使用{ {1}}首先。这是plnkr显示其工作原理。