Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question
    
Just put name as a property of an object on the scope. You sbould be good. Example $scope.viewModel = {} and set it here. –  PSL 2 days ago

2 Answers 2

up vote 0 down vote accepted

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"
share|improve this answer
    
Thanks, this clarifies! Shame on me that it was on top of this basic article, but I have a habit of inefficient speedreading. –  Gersom 2 days ago

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.