我有一个呈现长列表的指令。渲染工作得非常好而且快,现在我想用参数调用 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);
};
如何在 Controller 上调用 showdetails 函数?
谢谢曼努埃尔!
最佳答案
假设您引用的 Controller 具有指令的父作用域,您需要使用 Angular 的作用域函数表达式绑定(bind)来绑定(bind)该函数。请参阅#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)
属性,但如果您在 link
函数中将 html 渲染为 OP,则上述内容将按预期工作这样做需要首先使用 $compile
进行编译。这是 plnkr展示它是如何工作的。
关于javascript - Angularjs指令调用 Controller 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28832165/