user2130865
user2130865

Reputation:

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. 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?

Thanks Manuel!

Upvotes: 2

Views: 3606

Answers (1)

jsonmurphy
jsonmurphy

Reputation: 1600

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. See #8 here. 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:

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

Additional Reference: 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. Here's a plnkr showing how that works.

Upvotes: 3

Related Questions