Search code examples
javascriptangularjsangularjs-scopeangularjs-controller

Using object name when AngularJS variable is defined in $scope


Let's say we have an NameController in AngularJS. There you can define variables like this:

this.name = 'Joe';

Or:

$scope.name = 'Joe';

I always like to call all variables using the object notation:

<form ng-controller="NameController as nameCtrl">
  <input type="text" ng-model="nameCtrl.name">
</form>

This only works when I use the 'this' notation in the controller. When I use the $scope I have to call 'name' without the nameCtrl. to make it work.

Of course I'm missing some very fundamental basics here, but after doing some research I'm still stuck. How can I preserve as much object naming as possible in my HTML code?


Solution

  • You should use only one method at a time, See more detail on this link https://docs.angularjs.org/api/ng/directive/ngController

    Two different declaration styles are included below:

    • one binds methods and properties directly onto the controller using this: ng-controller="SettingsController1 as settings"
    • one injects $scope into the controller: ng-controller="SettingsController2"