Angularjs指令调用控制器函数

Angularjs directive call controller function

我有一个呈现长列表的指令。渲染工作得很好而且很快,现在我想用参数调用控制器上的一个函数。 我怎样才能做到这一点?

这是我的指令:

.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 的 作用域函数表达式绑定 来绑定该函数。参见 #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 展示它是如何工作的。