Crypt
Crypt

Reputation: 189

How to separate scopes of buttons inside a reusable directive

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 !!!

Upvotes: 1

Views: 962

Answers (1)

Mark Coleman
Mark Coleman

Reputation: 40863

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

Upvotes: 2

Related Questions