kathy
kathy

Reputation: 339

AngularJS execute controller function in directive template

I made a custom directive with AngularJS, and in the template I called a function in controller, but it didn't work.

thanks for your help :)

<div ng-contorller="myCtrl">
    <ng-selectbox my-function="myfunction()" items="codes"></ng-selectbox>
</div>

myapp.controller("myCtrl", function($scpoe){
  $scope.myfunction= function(){
    alert("123");
  };
});

myapp.directive("ngSelectbox", function(){
  return {
    restrict: "E",
    scope: {
      items: "=",
      myfunction: "&"
    },
    template:
    "<div id='selectbox'>" +
    "<ul ng-repeat='item in items'>" +
    "<li ng-click='myfunction()'>{{item.TYPE}}</li>" +
    "</ul>" +
    "</div>"
  };
});

Upvotes: 2

Views: 563

Answers (2)

Anand Gargate
Anand Gargate

Reputation: 489

Do not add calling brackets where you are using your directive , just use like this <ng-selectbox my-function="myfunction" items="codes"></ng-selectbox>

Upvotes: 3

Raja Sekar
Raja Sekar

Reputation: 2130

You should place your directive inside your controller wrapper like below.

<div ng-controller="myCtrl">
     <ng-selectbox my-function="myfunction()" items="codes"></ng-selectbox>
</div>

Upvotes: 0

Related Questions