1

I'm learning how to use AngularJS by building a small app. I'm a little confused about controllers and models. I have 3 controllers, 2 of which are nested.

<div ng-controller="Controller1 as Ctrl1">
    <div ng-controller="Controller2 as Ctrl2">
        <div ng-controller="Controller3 as Ctrl3">
        </div>
    </div>
</div>

I am using a different model for each controller to display data. All of the data is related in one way or another, so I am wondering if I should be using one model instead. And if so, where should it be defined?

For example, one controller might look like

(function() {

    angular
        .module('app')
        .controller('Controller1', Controller1);

    function Controller1() {

        this.data = data;
    }

    var data = [    
        {
            name: 'DATA 5',
        },
        {
            name: 'DATA 6',
        },
        {
            name: 'DATA 7',
        }
    ];
})();

where the model is defined in data. The other controllers would have models with different names.

5
  • Does the shared data in the model change often? Commented Jul 21, 2015 at 18:30
  • You should probably just use one service for all of the controllers to use so you an share data between controllers. Commented Jul 21, 2015 at 18:33
  • @Brant Some of the data in the lowest-nested controller changes every 10 seconds. Some data in the grandparent controller only changes every 60 seconds, but this data is not shared. Most of the changing data is in the lowest-nested child. Commented Jul 21, 2015 at 18:35
  • @Rob That's a good idea. It's just every example I have looked at so far has included the model in the controller. So I didn't know if that was a best practice or just for newbie simplicity. Commented Jul 21, 2015 at 18:37
  • 1
    The model in the controller is fine, but services are singletons so they'll persist the data. Commented Jul 21, 2015 at 18:53

1 Answer 1

1

Since you have related data that is shared (or not) and constantly changing every 10-60 seconds, I'd suggest using a single service. Within that service, instantiate however many data sets you need with matching getters/setters.

Services persist data so as one controller modifies the data in the service, the other controllers utilizing that service have access to the same updated data as well.

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

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.