Gersom
Gersom

Reputation: 671

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?

Upvotes: 1

Views: 867

Answers (2)

Dipak Patil
Dipak Patil

Reputation: 93

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"

Upvotes: 1

Ahmet Can G&#252;ven
Ahmet Can G&#252;ven

Reputation: 5462

Angular js has a feature ControllerAs. This is what you are using now. You are just referencing your nameCtrl object to NameController object. And you are accesing the name value with the clone of the controller object. Imagine that this is only a pointer to $scope

Here is a nice technical introduction: Angular Controllers

If you want to use objects everywhere, you can use Angular Service injected to your controller so you can easily call any object from your service in every controller.

Upvotes: 0

Related Questions