0

I've got a controller in Angular JS.

In this controller i've got a $scope.users property : it's an array of users.

This controller is used by two views: /users and /users/:id.

I've seen that the $scope.users models is init each time i come to an user view.

My question is simple how to do to get the $scope.users applied only to the /users view and not to the /users/:id view ?

I've done this with the $location.path method, but i don't know if it's the right way.

PS : I've got a factory to retrieve the users so i know it's a singleton ...

Thx for your answers.

Thomas Pons
  • 7,709
  • 3
  • 37
  • 55

2 Answers2

1

You could inject the $element object, and search through the dom to ensure you are on the right page.

You could inject the $location object and see if the url is on the right page.

You could add something to the template for /user so that it init's the array, and then user/:id wouldn't include that same call.

In your code, you could do something like:

angular.module('myapp').constant('users',[]);
angular.module('myapp').controller('UserCtrl', function(users){
    if(!users.length){
        //push some things into the bloody array
    }
});

I am not saying that this is the best of all the ways. It was the hardest to explain. It is similar to making a global variable, but you aren't making a global variable. You are making a constant variable on your angular module.

I am sure that there are more ways. These are just a few ways that I thought of.

frosty
  • 21,036
  • 7
  • 52
  • 74
  • Ok i see , so if i do it with the $location.path it's not an anti-pattern ? – Thomas Pons Jun 07 '13 at 10:35
  • I don't like the constants system, in a large app i can get well fifty or more of them ... The $location.path works well but it's an anti pattern i ll try the constant in module and i'll see thx ! – Thomas Pons Jun 08 '13 at 10:47
0

I've got the answer !

In fact AngularJS it's not a MVC framework but an MVVM framework. In this case the controller is the Model (in MVVM pattern), the $scope the ViewModel and the HTML the View (the ng-controller is the dataContext in pure .NET MVVM).

In this case a controller should have only a view !!

"In general, a controller shouldn't try to do too much. It should contain only the business logic needed for a single view."

http://docs.angularjs.org/guide/dev_guide.mvc.understanding_controller

Thx to you guys. Hope it helps.

Thomas Pons
  • 7,709
  • 3
  • 37
  • 55