Two way data binding with model instance in AngularJS

Posted By : Rajeev Kumar | 04-Dec-2014

Two Way Data Binding With Model Instance In AngularJS

To make a model instance we write a script in html where type is 'text/ng-template'

Ex:

<script type="text/ng-template" id="index.html">

//Content goes here.

</script>

 

In Angular Js we open this model instance as given below:

 

 $scope.openModel     = function (size) {

          var modalInstance = $modal.open({

          templateUrl: 'index.html',

          controller: 'indexCtrl',

          scope : $scope,

          size: size,

//If you want to pass a service reference to model instance, return it from resolve as given below

      resolve : {

                yourService : function(){

                    return yourService;

                },

        });

      }

;
 //and receive it as parameter in the model instance controller as

var modelCtrl = function($scope,service, $modalInstance){}

 

And we write the controller for this model instance like this:

var indexCtrl = function($scope, yourService, $modalInstance){

$scope.User = $scope.userName

//where user is your modal window scope variable and userName is parent controller scope variable.

//Code goes here.

}

 


Example : 

 

 <div ng-click="openModel()">Click to open Modal window</div> <script type="text/ng-template" id="index.html">

     <form>

    First Name:<input type = "text" ng-model="user.firstName"/>    

    Last Name:<input type = "text" ng-model="user.lastName"/>

</form>

     <div class="modal-footer">

         <button class="btn btn-primary" ng-click="ok(user)">OK</button>

         <button class="btn btn-warning" ng-click="cancel()">Cancel</button>

     </div>

 </script>

 

 

 $scope.openModel     = function (size) {

          var modalInstance = $modal.open({

          templateUrl: 'index.html',

          controller: 'indexCtrl',

          scope : $scope,

          size: size,

        });

      };

 

 

 var indexCtrl = function($scope, $modalInstance){

    $scope.userParent = $scope.user;

    $scope.user = {

            firstName : '',

            lastName : ''

    };

    

    $scope.ok = function (roleAndTemplate) {

              alert($scope.user.firstName+" "+$scope.user.lastName);

      });

          $modalInstance.close();

    };

 

 

     $scope.cancel = function () {

        $modalInstance.dismiss('cancel');

    };

}

 

Thanks

About Author

Author Image
Rajeev Kumar

Rajeev is an experienced Grails and angular Js Developer. Rajeev likes programming, cooking, net surfing, watching news.

Request for Proposal

Name is required

Comment is required

Sending message..