javascript - AngularJS - Why have more than one controller -


what reasons there have multiple controllers in angularjs application? i've built few angular apps , i've never encountered problem thought multiple controllers make things easier me.

i'm still bit of n00b, have never written unit test , code isn't manageable i'm sure it's ignorance. , i've heard other people have multiple controllers.

put way: how 1 know should create new controller?

from i've seen of angular application should have separate controllers separate scopes. instance, applications have user data. you'll want have data attached user model, inside user controller:

function userctrl ($scope) {     $scope.user = {         name: "bmorrow",         lastlogin: "4/16/2013"     }; } 

and template (our view) inside specific portion of applications structure. right side of navigation bar example, or on user details page. establish portion assigning controller using ng-controller. creates scope of said controller , binds corresponding models it. model (our data) connected view (the html) via controller.

suppose application has page user's written articles. can create controller restricted section of html holds article content.

function articlectrl ($scope) {     $scope.article = {         title: "hello world",         body: "lorem ipsum...."     }; } 

in trivial example above, combining both of controllers won't harm. once application begins grow, logically organizing controllers/views according data represents make code cleaner , easier understand. less unneeded complexity make everything easier on you. , using 1 controller unneeded complexity.

you can see illustrated in basarat's answer well. don't need use 1 controller per route, doing helps logically structure application.

so, answer question, should have 1 controller per category of data. users, articles, fruits, vegetables, transactions, , on.

read angular controllers , model-view-controller pattern more information if haven't already. hope helps.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -