0

UPDATE

here's the article where I saw the examples below: https://github.com/johnpapa/angular-styleguide

after re-reading the example I realized that a specific and unique scenario was being explained, thus this question may not be fully valid. I will not delete it, however, so that if anyone has any further knowledge, they can contribute and help the community.


I've been reading about angular best practices and I'm convinced after reading a few articles that the best approach is to use the controller as syntax:

angular.module('example', [])
.controller('somectr', somectr);

somectr.$inject =['$http'];

function somectr($http) {
 var vm = this;
 this.x;
}

however I saw an article that shows this syntax, but it also injects a scope:

somectr.$inject = ['$scope', '$http'];

function somectr($scope, $http) {
 var vm = this;
 this.x;
 this.y;

 $scope.someFunc = function() {}
}

I thought that using the controller as syntax means no need to use a scope object. What user case would require the controller as syntax but still make use of a scope object?

5
  • Probably that code is in the middle of conversion from scope syntax to controllerAs. :) Do you see is there any reason to use it in that piece of code in the article Commented Jul 28, 2015 at 20:30
  • none. when you do var vm = this; you are saying vm = $scope. can you link the article? Commented Jul 28, 2015 at 20:31
  • @ajmajmajma not exactly, it means $scope.aliasName = vm Commented Jul 28, 2015 at 20:33
  • @ajmajmajma here's the article, search for the string Directives and ControllerAs github.com/johnpapa/angular-styleguide. I just read the section again (I had read it last night) and I see that he's doing something unique here... so my question is probably invalid Commented Jul 28, 2015 at 20:35
  • @AbdulAhmad by someFunc did you mean $watch, if so yes they are not part of controller instance they are part of scope itself for which you would need to use scope? Commented Jul 28, 2015 at 20:35

1 Answer 1

3

An example of injecting $scope even if you are using controllerAs is when you want to pub/sub events.

If you want to Publish some events, you would use:

$scope.$broadcast('eventName', value)
$scope.$emit('eventName', value)

For Subscribing:

$scope.$on('eventName', function)

Take a further look at: https://docs.angularjs.org/api/ng/type/$rootScope.Scope

Another example would be if you are using $scope.$watch

There's a good article on controllerAs by ToddMotto: http://toddmotto.com/digging-into-angulars-controller-as-syntax/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.