问题
I have two controllers that are active on my page:
// For handling any changes made to the Recipe Window
ctrl.controller('recipeCtrl', ['$scope', 'view_service', 'recipe_service', function($scope, view_service, recipe_service) {
$scope.title = recipe_service.get_title();
}]);
ctrl.controller('setNameCtrl', ['$scope', 'view_service', 'recipe_service', function($scope, view_service, recipe_service) {
$scope.titleSet = recipe_service.get_title();
$scope.setName = function(){
recipe_service.set_title($scope.titleSet);
//view_service.set_view_url({url:"partials/typeWindow.tpl.html"});
};
}]);
Both controllers are pulling from this service:
serv.service('recipe_service', function(){
var recipe = {
title:"ace",
type:"",
market:[],
attribute:[]
};
return {
get_title: function() {
return recipe.title;
},
set_title: function(newTitle){
recipe.title = newTitle;
}
};
});
The second controller updates the "title" that the first controller is referencing. My problem is that once the second controller changes "title" in the service, the first controller is not updated to reflect the changes. What I am thinking that needs to happen is to some how refresh the first controller to pull in those new changes. Any suggestion on how to do so?
回答1:
// For handling any changes made to the Recipe Window
ctrl.controller('recipeCtrl', ['$scope', 'view_service', 'recipe_service', function($scope, view_service, recipe_service) {
$scope.curRecipe = recipe_service.recipe;
}]);
ctrl.controller('setNameCtrl', ['$scope', 'view_service', 'recipe_service', function($scope, view_service, recipe_service) {
$scope.curRecipe = recipe_service.recipe;
$scope.setName = function(){
//view_service.set_view_url({url:"partials/typeWindow.tpl.html"});
};
}]);
serv.service('recipe_service', function(){
return {
recipe : {
title:"ace",
type:"",
market:[],
attribute:[]
},
set_title: function(newTitle){
recipe.title = newTitle;
}
};
});
Using the same object throughout will work... this object can be defined in the service or you can use
angular.module("myApp",[]).value("myObject","Shared Value");
then inject this into you controllers like
angular.module("myApp").controller("MyCtrl",function($scope,myObject){console.log(myObject)})
I also posted a plnkr a while back showing some of the options:
http://plnkr.co/edit/ABQsAxz1bNi34ehmPRsF?p=preview
回答2:
Please find the below plunker
http://plnkr.co/edit/UQgAC8bzcJkmsfCMyP84?p=preview
来源:https://stackoverflow.com/questions/21863600/updating-a-controller-from-another-controller-angular