How can we watch expressions inside a controller i

2019-01-28 04:59发布

问题:

Since we cannot inject $scope inside controllers in Angular 1.4+, how can we watch expressions the way we used to do with $scope.$watch?

An attempt to inject $scope can be seen here ("Could not instantiate controller" error), and tutorials tells us that:

Angular wont be able to instantiate the controller if we pass $scope in it. It defines its observable properties on this. (source)

回答1:

I ran into this and needed an npm package; no good having everyone on the team build from source for the time being. We released an interim package on npm that fixes this issue: npm install loomio-angular-router@0.5.7

Note: you may need to rename ng-viewport to ng-outlet to get the interim package working.



回答2:

I have just found out that there is a bug on ngNewRouter causing this problem. It has been fixed, but haven't been released yet.

To workaround it, try this:

$ git clone git@github.com:angular/router.git
$ cd router
$ npm install
$ gulp angularify

after that, copy the dist files to your project



回答3:

you have $watch available in .activate. Check bellow (copy paste from my app).

function accountHistoryController (authService, accountFactory, CONSTANTS, $q, $routeParams) {

}
accountHistoryController.prototype.canActivate = function() {
    return !!this.authService.isAuthenticated();
}
accountHistoryController.prototype.activate = function($scope) {
    console.log ($scope);
    $scope.$watch('_this.currentPage', function(newPage){
    if (newPage == undefined) return;

});

}