我知道这已经发布过,但我仍然对如何针对我的具体问题实现这一点感到困惑。
我的第一个控制员:
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 :(得分:0)
使用Angular JS Services / Factories
示例示例如下所示
<强> 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? 强>