Shruti
Shruti

Reputation: 1574

AngularJS : how to get directive input field model value in controller?

I created a custom directive name kid. In that I have one input field with having usermodel object. I need to get its value in my controller. Can we get user model object in my controller. Actually I used to same directive in my view. I need to get both directive input values in my controller .

Here is my Plnkr

 var app =angular.module('Testappp',[]);
    app.controller('testcontroller',function(){

    })
    app.directive('kid',function(){

        return {

            restrict:"E",
            scope:{},
            template:"<input type='text' ng-model='usermodel'/>{{usermodel}}", 
        }

    })

Upvotes: 1

Views: 5599

Answers (2)

dhavalcengg
dhavalcengg

Reputation: 4713

Forked your plnkr. Passed two way data model from controller to directive. kid1 and kid2 are controller variable. Which will value you enter in text box.

    <!DOCTYPE html>
<html>

  <head>
    <script data-require="angularjs@*" data-semver="2.0.0" src="scruipt"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
  </head>

  <body ng-app="Testappp">
    <div ng-controller="testcontroller">
      <kid ng-model="kid1"></kid>
       <kid ng-model="kid2"></kid>
    </div>

</body>
<script>
    var app =angular.module('Testappp',[]);
    app.controller('testcontroller',function(){

    })
    app.directive('kid',function(){

        return {

            restrict:"E",
            scope:{
              ngModel: '=ngModel'
            },
            template:"<input type='text' ng-model='ngModel'/>{{ngModel}}",

        }

    })
</script>
</html>

Upvotes: 0

Arno_Geismar
Arno_Geismar

Reputation: 2330

I updated your plunkr: updatedMyPlunker

I am passing the usermodel to the kid directive via its isolated scope.

The = sign makes sure that the two models will update through two way data binding

     <body ng-app="Testappp">
        <div ng-controller="testcontroller">
          <kid usermodel="usermodel"></kid>
           <kid usermodel="usermodelSecondKid"></kid>
        </div>

    </body>    

     var app =angular.module('Testappp',[]);
            app.controller('testcontroller',function($scope){
              $scope.usermodel = '';
              $scope.usermodelSecondKid = '';
              $scope.$watch("usermodel", function(newvalue,oldvalue){
                console.log(newvalue);
              })
            })
            app.directive('kid',function(){

                return {

                    restrict:"E",
                    scope:{ usermodel: "=usermodel"
                          },
                    template:"<input type='text' ng-model='usermodel'/>{{usermodel}}",





                }

            })

Upvotes: 3

Related Questions