Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangular-ngmodel

pass the ng-model value to angular directive


I have a scenario where I have certain number of text-boxes and when I click on any of the text-box, its corresponding ng-model is to be printed on the browser console. I have written the following angular code:

<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.0/angular.min.js"></script>
<script>
    var app = angular.module("myApp", [])
    app.controller("myAppCtrl", function($scope){
        $scope.modelName = '';
    });
    app.directive("myDirective", function(){
        return{ 
            restrict: "A",
            link: function(scope, elem, attrs){
                scope.customFunc1 = function(){
                    console.log(attrs.ngModel);
                    scope.modelName = attrs.ngModel;
                };
            }

        }
    });
</script>
</head>
<body>
<div>
<input name="tb_1" type="text" ng-model="tb_1" ng-mousedown="customFunc1()" my-directive>
</div>
<div>
<input name="tb_2" type="text" ng-model="tb_2" ng-mousedown="customFunc1()" my-directive>
</div>

<div>
<input name="tb_3" type="text" ng-model="tb_3" ng-mousedown="customFunc1()" my-directive>
</div>
</body>
</html>

I have two questions: 1) Whenever I click on a text-box the ng-model of the third text-box is printed, irrespective which text-box I actually click. How do i fix that?

2) Is there a better way of accomplishing the above requirement?


Solution

  • The problem is your directive, It is using single scope.

    For solving your problem you need to make your directive to use isolated scope by mentioning scope: true inside directive & for more flexibility I'd suggest you to make ngModel attribute as required using require: 'ngModel' as you directive is fully dependant on it. By making field required you can get ngModel inside directive pre/post link function. and you can played with ng-model variable value or validation anytime

    Directive

    app.directive("myDirective", function() {
      return {
        restrict: "A",
        require: 'ngModel',
        scope: true,
        link: function(scope, elem, attrs, ngModel) {
          scope.customFunc1 = function() {
            console.log(attrs.ngModel);
            scope.modelName = attrs.ngModel;
          };
        }
      }
    });
    

    Working Plunkr