简体   繁体   English

AngularJS指令调用控制器功能

[英]Angularjs directive call controller function

i have a directive which renders a long list. 我有一个指令,使一个长长的清单。 The Rendering works pretty fine and fast, now i would like to call a function on the Controller with Parameters. 渲染工作的非常好和快速,现在我想在带参数的Controller上调用一个函数。 How can i achieve this? 我怎样才能做到这一点?

Here is my directive: 这是我的指令:

.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);
};

How can i call the showdetails function on my Controller? 如何在控制器上调用showdetails函数?

Thanks Manuel! 谢谢曼纽尔!

Assuming the controller you're referring to has the parent scope of the directive, You need to bind the function using angular's Scope Function Expression Binding . 假设您要引用的控制器具有指令的父范围,则需要使用angular的Scope Function Expression Binding绑定函数 See #8 here . 请参阅此处的 #8。 So it could look something like: 因此可能看起来像:

.directive("slheats", function () {
  return {
    ...
    scope: {
      slheats: "=",
      internalShowdetails: "&"
    },
    link: function (scope, element, attrs) {
      ....
      line += "<div class='name'><button ng-click='internalShowdetails()'>" + entry.Name + "</button></div>";
      ....
  }
});

Then in your html: 然后在您的html中:

<div slheats="something" internal-show-details="showdetails(a, b, c)"></div>

Additional Reference: http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/ 附加参考: http : //onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/

Update: 更新:

So the above will work as expected provided you are using the template(Url) property on the directive but if you are rendering the html within your link function as OP is doing it needs to be compiled with $compile first. 因此,如果您在指令上使用template(Url)属性,则上述方法将按预期工作,但是如果在OP进行link函数内呈现html时,则需要先使用$compile Here's a plnkr showing how that works. 这是显示其工作原理的plnkr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM