2013-06-28 19 views
35

我想在應用程序加載時設置默認狀態時執行一些操作。所以我試圖在Module對象上使用run方法。當我嘗試訪問$ scope變量時,雖然我的控制檯中收到了「Uncaught ReferenceError:$ scope is not defined」消息。

請看下面的例子http://jsfiddle.net/F2Z2X/1/

app = angular.module('myapp', []); 

app.controller('mycontroller', function($scope){ 
    $scope.data = { myvariable: 'Hello' }; 
}); 

app.run(
    alert($scope.data.myvariable)) 
); 

我要對所有這一切錯了嗎?

例如,我想在開始時運行一次watchAction函數,以隱藏尚未調用的UI元素,但watchAction函數沒有$ scope對象,因爲它沒有被調用觀看方法,所以我必須通過它,但唉,它不可用。

+0

.run在初始化開始時運行一次。我認爲在這一點上有一個$範圍是不合理的。你可以傳入$ rootScope tho。 –

回答

75
app.run(function ($rootScope) { 
    $rootScope.someData = {message: "hello"}; 
}); 

你只能得到$rootScope注入servicesrun功能,因爲每個child scope是從它的父作用域繼承和頂層範圍rootScope。因爲注入的任何範圍都是不明智的。只提供根作用域。例如:

+0

1問題:如果我在'$ rootScope.on('myevent',function(){})''運行塊中添加任何事件處理程序'....我應該如何調用$ destroy?在$ rootScope本身上?因爲如果我不這樣做,我得到lint錯誤....並且不能在運行塊中使用$ scope。 – Pawan

3
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; 
} 

例如, https://github.com/shekkar/ng-book/blob/master/7_beginning-directives/current-scope-introduction.html

這是簡單的流程,我們有rootScope,parentScope,childScope。在每一節中我們都分配了相應的作用域變量。我們可以在childScope的parentScope,rootScope和parentScope中訪問$ rootScope。

+0

你可以在閱讀後編輯你的文章嗎? http://stackoverflow.com/editing-help – brasofilo

+0

對於幾乎一年前已經回答並接受的問題添加新答案,有什麼意義? – ivarni

+3

我想分享我的知識,在這個例子中它解釋了rootScope以parentScope和parentScope爲childScope和url解釋競爭html代碼,我希望這可能對@Tristan和其他人有幫助 – Shekkar

相關問題