I know this has been posted before but I am still confused on how to achieve this for my specific problem.
my first controller:
myApp.controller("buttonCtrl", function($scope){
$scope.johnny = [
{quote: "Anything for My Princess", controller: Princess},
{quote: "Don't Even Ask", controller: DontAsk}];
}
Now I would like to use the $scope.johnny object in this controller:
function Princess($scope){
$scope.play = function(){
//use $scope.johnny.quote or something of the sorts in here
}
}
How would this be done? I have seen posts where $rootScope or services are used; however, how would I implement one in my case.
Thanks a lot.
Nidhish Krishnan
20.8k6 gold badges67 silver badges78 bronze badges
asked May 12, 2014 at 14:00
benjipelletier
6555 gold badges11 silver badges30 bronze badges
-
@Beterraba Yes, I believe it is, but I am still unsure how to accomplish this. Thanksbenjipelletier– benjipelletier2014年05月12日 14:02:45 +00:00Commented May 12, 2014 at 14:02
1 Answer 1
Use Angular JS Services/ Factories
A sample example is shown below
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]));
}
});
Also take a look at this stuff
answered May 12, 2014 at 14:07
Nidhish Krishnan
20.8k6 gold badges67 silver badges78 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
benjipelletier
Thank you for the well explained answer. It helps a lot!
benjipelletier
No problem, sorry it wouldn't let me it do it that early.
Explore related questions
See similar questions with these tags.
lang-js