1

I have this form. This form contains many many inputs like first name, last name, job title, notes, state, department, documents, supervisor...and so on

Originally I had a controller like so

    app.controller("titleCtrl", function ($scope)
    {      
           $scope.FirstName = ...
           $scope.LastName = ...
           $scope.Notes = ....
           $scope.JobTitle = ...
           $scope.Department = ...
           $scope.Supervisor = ...
           $scope.Documents = ...
           $scope.ID = function(data){
                } 
           //and 15 more fields......            
});

I've learned that declaring variables on the scope like this isn't really the best practice. My question is what is best practice? What's the best/optimal way for declaring 20 or so variables within a controller?

prawn
  • 2,643
  • 2
  • 33
  • 49
  • Some very good advice in the answers below. You should be aware of the [dot problem](http://stackoverflow.com/questions/17606936/angularjs-dot-in-ng-model) – Gruff Bunny Apr 13 '14 at 17:38

3 Answers3

3

First of all, $scope is not your model. It is just a placeholder for model. Lets say you want to show user information, then you should have like this

$scope.user = {
    firstName: 'Joe',
    lastName: 'Masan',
    jobTitle: 'Engineer',
    age: 22,
};

This is the best practice of having model(here it is user.) in the scope. You SHOULD NOT directly assign field in the $scope object. In terms of performance, AngularJS works well below 200 properties in the scope. Since AngularJS has a digest cycle, it will always hit the performance when you have large number of fields.

Great video about best practices from AngularJS creator https://www.youtube.com/watch?v=ZhfUv0spHCY

Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
0
  • If variables, then declare them in the beginning of the function block.
  • If properties, create a namespace and add it in that, so it can be accessed elsewhere globally and at same time namespace will save it from adding to window object directly.
vivek_nk
  • 1,590
  • 16
  • 27
0

Depends what you mean by optimal.

Angular Forms provide your variables on the fly. when adding ng-model to an input element. so:

<input name="first_name" ng-model="first_name">

first_name is available when you need it.

But it depends what you want to do with it.

if you don't need to change every variable you can skip declaring variables all together and simply use javascript native Form Data object

raam86
  • 6,785
  • 2
  • 31
  • 46