0

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
4
  • 1
    try putting the veriable in $rootScope or use a service to fetch veriable value. Commented Jul 15, 2015 at 7:01
  • 1
    possible duplicate of Angular: Share data between controllers Commented Jul 15, 2015 at 7:02
  • using a service is better solution, here you have some demos and tutorials thinkster.io/a-better-way-to-learn-angularjs/services Commented Jul 15, 2015 at 7:05
  • How can I pass more ng-model values? Commented Jul 15, 2015 at 7:39

2 Answers 2

1

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 {

   }
  });`
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.