3
<div ng-controller="aCtrl">
 <input type="text" ng-model="person" />
 <button type="button" ng-click="Search()">XXX</button>
</div>

<div ng-controller="bCtrl">
 <input type="text" ng-model="car" />
</div>

In the onclick event Search() how do I gain access to $scope.car, which is inside another controller?

2
  • possible duplicate of Can one controller call another in AngularJS? Commented Sep 4, 2013 at 18:43
  • Not sure if you can..I know creating a shared service would be one way to go. Commented Sep 4, 2013 at 18:44

1 Answer 1

4

Here's a simple solution:

<div ng-init='model={ person: "", car: "" }'>
  <div ng-controller="aCtrl">
   <input type="text" ng-model="model.person" />
   <button type="button" ng-click="Search()">XXX</button>
  </div>

  <div ng-controller="bCtrl">
   <input type="text" ng-model="model.car" />
  </div>
</div>

Simply go one step higher on the $scope and set your data on the parent scope. Notice that I updated the values bound to your inputs to reference properties of the new model object. By doing this, you reference an object on that parent scope rather than scalars, so that the reference to that object gets prototypically inherited by the child scopes. If this doesn't make much sense, the tl;dr version is:

Generally speaking, you want to make sure that your ng-model directives contain a dot.

You could also define an angular service to share data between the two controllers, but that's possibly overkill for what you need.

Sign up to request clarification or add additional context in comments.

4 Comments

I'd go with the service option, if you continue using angular you will need to know how to do it, and it feels more natural to me at least. . .
Perhaps. Given the ng-model usage, I figured illustrating the necessity of the dot in ng-model was probably the most edifying to the OP. In AngularJS, like with anything, there exists a wide variety of feline hide removal techniques.
And how can I access that model.person from any controller's javascript?
@Arkanoid you might want to open a new question for that.

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.