Getting $scope object in Angular's run() method

前端 未结 2 756
难免孤独
难免孤独 2020-12-28 12:50

I\'d like to do some stuff when my app loads to set up the default state. So I\'m trying to use the run method on the Module object. When I try to access the $scope variable

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-28 13:48

    var app = angular.module('myApp', []);
    app.run(function ($rootScope) {
        // use .run to access $rootScope
        $rootScope.rootProperty = 'root scope';
    });
    
    app.controller("ParentCtrl", ParentCtrlFunction);
    app.controller("ChildCtrl", ChildCtrlFunction);
    function ParentCtrlFunction($scope) {
        // use .controller to access properties inside ng-controller
        //in the DOM omit $scope, it is inferred based on the current controller
        $scope.parentProperty = 'parent scope';
    }
    function ChildCtrlFunction($scope) {
        $scope.childProperty = 'child scope';
        //just like in the DOM, we can access any of the properties in the
        //prototype chain directly from the current $scope
        $scope.fullSentenceFromChild = 'Same $scope: We can access: ' +
        $scope.rootProperty + ' and ' +
        $scope.parentProperty + ' and ' +
        $scope.childProperty;
    }  
    

    for Eg. https://github.com/shekkar/ng-book/blob/master/7_beginning-directives/current-scope-introduction.html

    It is simple flow ,we have rootScope,parentScope,childScope .in each section we are assigning the corresponding scope variables.we can access the $rootScope in parentScope, rootScope and parentScope in childScope.

提交回复
热议问题