How to separate scopes of buttons inside a reusable directive

岁酱吖の 提交于 2019-12-11 11:17:30

问题


I need to have a reusable directive with several buttons.But my problem is when I try to use the same directive multiple times the buttons binds to one single scope. For example see the code below:

<body ng-controller="MainCtrl">
  <test></test>
  <test></test>
</body>

Code for test directive is

app.directive("test",function(){

return{
    restrict:"E",
    scope:{
          },
    template:"<input type='button' value='click me!' onclick='clickD()'>",
    controller:function($scope){
        clickD=function()
        {
            alert($scope.$id);
        }
    }
}
})

You can see the example here as well link

Now How do I separately the scopes. My actual problem is pretty clumsy so i simplified it till this level.Please help me !!!


回答1:


You need use ng-click and not onclick, also place the clickD() function on your $scope

app.directive("test", function () {

    return {
        restrict: "E",
        scope: {},
        template: "<input type='button' value='click me!' ng-click='clickD()'>",
        controller: function ($scope) {
            $scope.clickD = function () {
                alert($scope.$id);
            }
        }
    }
})

updated plnkr



来源:https://stackoverflow.com/questions/18317322/how-to-separate-scopes-of-buttons-inside-a-reusable-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!