Praveen
Praveen

Reputation: 56509

variable is not acting independently when using multiple copies of same angular directive

I'm trying to create a directive with 2 radio button binding with update variable. Now I planned to use the same directive in once again. Now the problem is the scoped variable update is not acting independently.

Below is the mock example I have created,

var myApp = angular.module('myApp',['ngRoute']);

myApp.directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: false,
        template: '<div><span>A new directive</span>'
                    + '<input name="updated" type="radio" ng-model="con.isUpdate" ng-checked="con.isUpdate" />'
                    + '<input name="updated" type="radio" ng-model="con.isUpdate" ng-checked="!con.isUpdate" />'
                    + '</div>',
        controller: controller,
        controllerAs: 'con'
    };

    function controller ($scope) {
        $scope.isUpdate = true;
    }
});
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
        <script src="index.js"></script>
    </head>
    <body ng-app="myApp">
        <div my-directive></div>
        <br/>
        <div my-directive></div>
    </body>
</html>

Running the code snippet will give a clear picture of the problem.

Upvotes: 0

Views: 39

Answers (1)

MattSizzle
MattSizzle

Reputation: 3175

The radio inputs have the same name so the browser is "grouping" them if you will and applying updates to the radios based on name.

An easy way to fix this is to pass the name to the directive to apply to the radios, or (as shown below) create different directives.

function Directive(name) {
    return {
        restrict: 'A',
        scope: false,
        template: '<div><span>A new directive</span>'
                    + '<input name="' + name + '" type="radio" ng-model="con.isUpdate" ng-checked="con.isUpdate" />'
                    + '<input name="' + name + '" type="radio" ng-model="con.isUpdate" ng-checked="!con.isUpdate" />'
                    + '</div>',
        controller: controller,
        controllerAs: 'con'
    };

    function controller ($scope) {
        $scope.isUpdate = true;
    }
}

myApp.directive('myDirective', new Directive('updated'));
myApp.directive('myDirective2', new Directive('updated-alt'));

Upvotes: 2

Related Questions