How can we watch expressions inside a controller i

2019-01-28 05:04发布

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)

3条回答
该账号已被封号
2楼-- · 2019-01-28 05:11

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.

查看更多
我只想做你的唯一
3楼-- · 2019-01-28 05:18

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;

});

}
查看更多
做自己的国王
4楼-- · 2019-01-28 05:37

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

查看更多
登录 后发表回答