user4207046
user4207046

Reputation:

Angular new router Inject $scope to controller

How i can use $scope to gain access to functions likes $watch, $emit, $digest?

When i am trying to do this:

class HomeController {
  // @ngInject
  constructor($scope) {
    $scope.country = {};
    $scope.countries = [
      {name: 'Afghanistan', code: 'AF'},
      {name: 'Åland Islands', code: 'AX'},
      {name: 'Albania', code: 'AL'},
      {name: 'Algeria', code: 'DZ'},
      {name: 'American Samoa', code: 'AS'},
      {name: 'Andorra', code: 'AD'},
      {name: 'Angola', code: 'AO'},
      {name: 'Anguilla', code: 'AI'}
    ];
  }
}

export default HomeController;

I am getting an error: Could not instantiate controller HomeController

Upvotes: 1

Views: 485

Answers (2)

Tomer
Tomer

Reputation: 4481

NEWER ANSWER
With the new router the controller gets initiated before the child scope is being created.
The child scope (the controller's scope) is created when the activate method is being called - that is - after the actual compilation of the view is finished. Therefore, it is simple impossible the inject $scope - it is simple created later.
Long story made short... There is a better, built-in solution for this.
Instead of assigning your properties to the non-existing-yet $scope, simply assign them on the "this" variable - the controller instance variable. Then on the view, you can use them by referring the controller name:

angular.module('app.home').controller('HomeController', HomeController);

function HomeController() {
    this.name = "tomer";
}

And now on the template html:

<div>
    <h1>{{home.name}}
</div>

Makes sense?

Upvotes: 0

codeful.element
codeful.element

Reputation: 242

Had the same issue when attempting to use $watch for data binding.

At this time of writing, the current version of Angular New Router (v0.5.3) could not instantiate controller with $scope injected. The issue was logged on github.

According to a separate thread, there is an interim package on npm with the fix of this issue. Check out zVictor's post for instructions.

Upvotes: 1

Related Questions