2

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>"
  };
});
1
  • where is your controller Commented Mar 26, 2015 at 9:48

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

thank you, tried but didn't work :( and what if I want to pass parameter through myfunction?
Hey, got the solution, you have used my-function attribute, and in directive myfunction instead of myFunction , just replace myfunction with myFunction and it will work, see working example plnkr.co/edit/1CblTUHoMTZMKLOf4INE?p=preview
THANK YOU SO MUCH! It really had confused me for a long time... thank you for solving it.
Yes sure, check working example(check console) : plnkr.co/edit/1CblTUHoMTZMKLOf4INE?p=preview
Just modify function scope to '='(two way binding).
|
0

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>

1 Comment

Yes, it is inside my controller, sorry I didn't mention that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.