2014-05-12 138 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

相关问题