2014-05-12 106 views
-2

我知道這已經發布之前,但我仍然困惑如何實現這個我的具體問題。AngularJS - 在控制器之間共享變量

我的第一個控制器:

myApp.controller("buttonCtrl", function($scope){ 
    $scope.johnny = [ 
     {quote: "Anything for My Princess", controller: Princess}, 
     {quote: "Don't Even Ask", controller: DontAsk}]; 
} 

現在我想用$ scope.johnny對象在此控制器:

function Princess($scope){ 

    $scope.play = function(){ 
    //use $scope.johnny.quote or something of the sorts in here 
    } 
} 

這將如何做呢?我看過使用$ rootScope或服務的帖子;然而,我將如何執行一個在我的情況。

非常感謝。

+0

@Beterraba是的,我相信它是,但我仍然不確定如何做到這一點。謝謝 – benjipelletier

回答

0

使用角JS服務/工廠

樣品示例如下所示

Working Demo

HTML

<div ng-app='myApp'> 
    <div ng-controller="ControllerOne"> 
     <button ng-click="getUserOne()">User One</button> 
    </div> 
    <div ng-controller="ControllerTwo"> 
     <button ng-click="getUserTwo()">User Two</button> 
    </div> 
</div> 

SCRIPT

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

app.factory('userFactory', function() { 
    return { 
     users: [{ 
      userId: 1, 
      userName: "Jhonny" 
     }, { 
      userId: 2, 
      userName: "Sunny" 
     }] 
    } 
}); 

app.controller('ControllerOne', function ($scope, userFactory) { 
    $scope.getUserOne = function() { 
     alert(JSON.stringify(userFactory.users[0])); 
    } 

}); 

app.controller('ControllerTwo', function ($scope, userFactory) { 
    $scope.getUserTwo = function() { 
     alert(JSON.stringify(userFactory.users[1])); 
    } 

}); 

也看看這個東西

How can I pass variables between controllers in AngularJS?

+0

謝謝你解釋得很好的答案。它有很大幫助! – benjipelletier

+0

沒問題,對不起,它不會讓我這樣做的那麼早。 – benjipelletier

相關問題