0

I'm implementing an AngularJS directive on Angular 1.4.12 using the controllerAs and bindToController "pattern" in order to have a clean controller which doesn't depend on $scope. However I still find hard to get rid of $scope on these lines:

$scope.$on( '$destroy', function() {...} );
$scope.$on( '$stateChangeSuccess', function() {} );

Any idea how to handle this case?

Thanks

gabric
  • 1,865
  • 2
  • 21
  • 32
  • 1
    Possible duplicate of http://stackoverflow.com/questions/28344131/using-watch-without-scope-controller-as-syntax – Arun Ghosh Aug 05 '16 at 08:13
  • I read that the lifecycle hooks have been introduced in Angular 1.5.x. Probably that is what I'm looking for. https://docs.angularjs.org/api/ng/service/$compile. Unfortunately I can't upgrade my project to AngularJS 1.5.x – gabric Aug 05 '16 at 08:21
  • lifecycle hooks are currently only available to components – svarog Aug 05 '16 at 08:25
  • you will have to keep using $scope for events... its kind of service providing you these services – harishr Aug 05 '16 at 08:33
  • 1
    @svarog They are available in directives. Components are sugared directives. – Estus Flask Aug 05 '16 at 10:20
  • See this https://github.com/toddmotto/angular-component. But as the answer already says, there's no valid reason to zealously eradicate $scope. `$scope.$on` is the way the events work in Angular. – Estus Flask Aug 05 '16 at 10:24

1 Answers1

5

The idea behind not using $scope is to:

  • not pollute the HTML with variables that have no context and potentially have conflicting variable names in the same scope.

    ng-model="name" VS ng-model="userController.user.name"

  • not pollute you javascript code by preceding every variable and function with $scope

If you need to broadcast events or watch changes, it's perfectly fine to use $scope (especially if you have no alternative like .components in angular 1.5)

See $scope as a service provided to you by Angular just like $window or $state. If you need it, you can use it. (but don't go and put code in there, even if you can)

gyc
  • 4,300
  • 5
  • 32
  • 54
  • 2
    You are spot on. The only addition I would make is that the new ui.Router deprecates the $stateChangeSuccess event in favor of a onSuccess subscription hook: https://ui-router.github.io/docs/latest/classes/transition.transitionservice.html#onsuccess – Martin Aug 05 '16 at 14:18
  • Thanks for point out the deprecation. Unfortunately we're currently using ui-router v 0.2.15 which doesn't offer the possibility to hook into onSuccess – gabric Aug 05 '16 at 15:33