Merbin Joe
Merbin Joe

Reputation: 688

How can I access the another ng-controller ng-model from another ng-controller?

I want to access the ng-model from another ng-controller is it possible and how?. In the following code I am using two controller, first controller having mddl1 and another one controller don't have any other model. But I want to access the model value from 2nd controller method.

<div ng-controller="cnt_fnt">
<select id="dflfnt" ng-model='mddl1' ng-options='option.name for option in ddl1options.data'> 
</select>
</div>
<div ng-controller="ctrl_opsection" ng-model="opmodel">
</div>
<script>
----
.controller('cnt_fnt', ['$scope', function ($scope) {
$scope.ddl1options={
data:[
{value:"Georgia, serif",name:"Style 1"},
{value:"'Times New Roman', Times, serif",name:"Style 3"},
{value:"Arial, Helvetica, sans-serif",name:"Style 4"}
]};
  alert($scope.mddl1.value); //Here I Can Access the dropdown value
}])
.controller("ctrl_opsection",["$scope",function($scope){
    alert(cnt_fnt.mddl1.value); //I want to access here that dropdown value 
}]);
</script>

I am tried to access the ng-model value from another ng-controller value like following code.

alert(cnt_fnt.mddl1.value); //controller_name.modelname

Upvotes: 0

Views: 69

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

You can find best practice code at here. This will become best solution for you.

Upvotes: 0

user4898717
user4898717

Reputation: 66

In common, use service . When parentCtrl send data to childCtrl, can use $broadcast $on.Conversely, can use $emit $on.

 `controller('cnt_fnt', ['$scope','inter', function($scope,inter){
    inter.data = $scope.mddl1.value;
  }])
  .controller('dockCtr', ['$scope', 'inter', function($scope, inter){
     alert(inter.data)
  }]);

  app.service('inter', function(){
   return {

   }
  });`

Upvotes: 1

Related Questions