Two way data binding with model instance in AngularJS
Posted By : Rajeev Kumar | 04-Dec-2014
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Rajeev Kumar
Rajeev is an experienced Grails and angular Js Developer. Rajeev likes programming, cooking, net surfing, watching news.