javascript - Angularjs指令调用 Controller 函数

标签 javascript angularjs controller directive

我有一个呈现长列表的指令。渲染工作得非常好而且快,现在我想用参数调用 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/

相关文章:

javascript - 在 AngularJS View 中的移动网络中显示原生广告时出现问题

c# - ASP.NET MVC 下载图像而不是在浏览器中显示

javascript - 两个物体的深度差异

javascript - 不能在子方法 :{} vue. js 中使用传递的 Prop

javascript - 原型(prototype)上的属性受到不同的影响

javascript - $compile 不更新动态生成的 html 运行时

javascript - 包含 HTML 和 JavaScript 标记作为文本的 HTML 选择控件

angularjs - AngularJS 上的条件渲染

php - Laravel 管理员编辑路线不起作用。返回 404

c# - 更多 Controller 但操作更少或 Controller 更少但操作更多