Search code examples
angularjsangularjs-scope

AngularJS: Correct way to define a model?


I am trying to find the best way to define a model. I have set my ng-model to

    model.test

and sure enough it seems to work, I did a standard

    alert($scope.model.test);

Do I always have to refer to it has $scope?

So when do I need to set this up in the controller i.e.

    $scope.model ={};

If I want to populate from the controller I can setup something like

    $scope.model = {name: 'test', age: 56};

but what if I would like to create the model ensuring that it had only "name" and "age" set has available properties but containing NO VALUE?

Is it normal to have the model created directly on the scope? Can I not have my models created separately in a file?

As you can see I have it working, but I am not sure which way I should be going.


Solution

  • $scope.model = {};
    $scope.model.name = ''; // default value
    $scope.model.age = ''; // default value  
    

    Then you can modify it like this:

    $scope.model.name = 'test';
    $scope.model.age = 56;  
    

    Or add more attributes:

    $scope.model.foo = 'bar';