简体   繁体   中英

Alias the AngularJS $scope object in a controller

Without getting into the details of why, I need to provide an alias for $scope in my controllers. Instead of injecting and decorating $scope I'd like for the users to instead be able to inject view and have it have the same effect.

Based on my understanding of angular, $scope is created by a $scopeProvider which is a factory registered at configuration time of the angular app. I'm assuming that I need to register a viewProvider and set it equal to the $scopeProvider but I haven't had luck with what I've been trying. Any ideas?

FYI: I'm not looking for something like ['$scope', function(view){... , the ideal solution would work with ['view', function(view){... . The view object would act exactly like $scope , two way binding, etc.

If you are teaching AngularJS , you should actually avoid using $scope and use controller as syntax -- See this awesome Angular Style Guide by John Papa for explanation .

That would also solve your problem :)

There is no such a thing as $scopeProvider , scopes are created using the $new method, every scope has access to this method through inheritance (delegation to be precise). When you ask for a $scope in a controller, the $scope is created dynamically using it's parent $scope $new method and injected under that name. To invoke the aforementioned behavior for a different name you would have to play with angular internals.

I was able to solve it in my app's config section. In my controllers now I can use $scope or view and they'll have the same meaning.

   $routeProvider
    .when('/Index', {
        templateUrl: "/views/index.html",
        controller: ['$scope', '$controller', function($scope, $controller){
            $controller("IndexController", {$scope:$scope, view: $scope});
        }]
    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM