AngularJS在指令模板中执行控制器功能

时间:2015-03-26 09:45:29

标签: javascript angularjs directive

我用AngularJS制作了一个自定义指令, 在模板中我在控制器中调用了一个函数, 但它没有用。

感谢您的帮助:)

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

2 个答案:

答案 0 :(得分:3)

不要在使用指令的地方添加调用括号,只需使用<ng-selectbox my-function="myfunction" items="codes"></ng-selectbox>

答案 1 :(得分:0)

您应该将指令放在控制器包装器中,如下所示。

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