2015-02-11 39 views
1

我在爲Angularjs設置$ rootScope時遇到了問題。

下面是我的功能

App.controller('Controller', 
function (UtilityService, $rootScope) { 

var setSession = function() { 

    $rootScope.test = "yes"; // <-- I get this 

    UtilityService.getSession().success(
    function() {  
    $rootScope.test = "No"; // <-- I don't get this How do I get/set this value?  
    });  
}; 

setSession(); 

}); 

附加信息:

其中一個可能的工作方式是建立被多個控制器之間交互的服務。有沒有人知道如何通過返回http.get json對象的服務來做到這一點。

我無法在服務中實例化的控制器中獲取動態範圍。

+0

我會用你的情況$範圍,無論是訪問‘測試’是在同一個控制器。 – 2015-02-11 20:11:13

+0

那麼你可以設置$ rootScope爲$ scope?我需要訪問不同控制器中的「範圍」。 – Demodave 2015-02-11 20:27:52

+0

可能希望使用服務在控制器之間共享數據,以免污染'$ rootScope'。但'$ rootScope'應該可以訪問。 – 2015-02-11 21:27:54

回答

2

爲了解決我的問題,我不得不

1)通$ rootScope到我的第二個控制器

App.controller($ rootScope){

2)設置我的第二個控制器的功能,以$ rootScope

$ rootScope.functionCall = function(){};

3)我通過我的價值公用控制器內通過我的結果設置爲$ rootScope($ rootScope.orderId)

$rootScope.functionCall = function() { 
Service.getItems($rootScope.orderId).success(
    function(results) { 
     $scope.items = results; 
    }); 
}; 

4),我循環,把它們解析,並將它們設置爲$ rootScope,如#3所示我正在初始化「$ rootScope.orderId」

angular.forEach(results, function (value, key) { 
     if (key != null) { 
     $parse(key).assign($rootScope, value); 
     } 
    }); 

5)我在我的服務調用中重新調用控制器的功能!這就是我把變量「在範圍內」的魔力

$ rootScope.functionCall();

6)我也測試,看看是否存在功能造成不同頁面使用的公用代碼,但可能沒有執行

如果函數(typeof運算$ rootScope.functionCall ==「功能「)

var setSession = function() { 

    UtilityService.getSession().success(
    function (results) {    

    // Place the rootscope sessions in scope 
    angular.forEach(results, function (value, key) { 
     if (key != null) { 
     $parse(key).assign($rootScope, value); 
     } 
    });     

    // Have to bypass "scope" issues and thus have to execute these fns() 
    if (typeof $rootScope.functionCall == 'function') { 
     $rootScope.functionCall(); 
    } 

}); 

}; 
setSession(); 
0

正如我以前寫的,我會盡可能使用$範圍,如果您需要跨多個控制器共享數據,您可以使用服務。代碼應該是這樣的:

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

app.factory('$http', 'myService', function ($http, myService) { 
    var customers = {}; 
    $http.get("http://www.w3schools.com/website/Customers_JSON.php") 
     .success(function (response) { 
      customers = response; 
     }); 

    return { 
     customers: customers 
    }; 
}); 

app.controller('controller_one', function($scope, myService) { 
    $scope.serv = myService.customers; 
}); 

app.controller('controller_two', function($scope, myService) { 
    $scope.serv = myService.customers; 
}); 
+0

我已經試過類似這樣的東西,如果服務連接到http.get,那麼如何使用它。 – Demodave 2015-02-12 14:12:37

+0

同樣,在我的示例中,服務初始化數據本身,但它可以啓動http.get請求。 – 2015-02-12 14:16:42

+0

你能舉個例子嗎? – Demodave 2015-02-12 15:34:32