我想调用一个函数或更改另一个控制器内的变量/ s的值。我在网上查找了解决方案,并了解我必须创建一个service
并在控制器中使用它,但是我无法理解service
如何访问$scope.home_main
和$scope.home_main
变量,因为它们位于不同的scope
。
JS
app.controller('Controller1', function ($scope, $window) {
$scope.toggle = function() {
$scope.home_main = !$scope.home_main;
$scope.full_page_place_holder = !$scope.full_page_place_holder;
};
});
app.controller('Controller2', function ($scope, $window) {
$scope.onTabSelect=function(){
// here I want to call toggle function which is inside another controller.
};
});
更新了HTML
<div ng-controller="Controller1">
<div ng-hide="home_main"></div>
</div>
<div ng-controller="Controller2">
<div ng-hide="full_page_place_holder"></div>
</div>
答案 0 :(得分:1)
您可以按照以下方式创建服务,
angular.module('someApp').service('shareDataService', function() {
var popup;
var setDetails = function(param) {
popup = param;
};
var getDetails = function() {
return popup;
};
return {
setDetails: setDetails,
getDetails: getDetails,
};
});
此服务无法访问两个控制器的$ scope变量,而是可以调用getDetails和setDetails来获取和设置服务中的变量。
假设您要将“home_main”的值从controller1发送到controller2,在controller1中,您调用服务函数setDetails
app.controller('Controller1', function ($scope, $window, shareDataService) {
$scope.toggle = function() {
$scope.home_main = !$scope.home_main;
$scope.full_page_place_holder = !$scope.full_page_place_holder;
shareDataService.setDetails($scope.home_main);
};
});
并在controller2中,通过调用服务
获取值app.controller('Controller2', function ($scope, $window) {
var home_main_value = shareDataService.getDetails();
});
你也可以为功能做类似的事..... 希望它有所帮助
答案 1 :(得分:0)
你误解了概念服务将有一个由两个控制器共享的变量: - $ scope对于控制器是本地的,不能被另一个控制器访问: -
例如: -
myApp.factory('Data', function () {
var data = {
home_main : ''
};
return {
gethome_main : function () {
return data.home_main ;
},
sethome_main : function (home_main ) {
data.home_main = home_main ;
}
};
myApp.controller('FirstCtrl', function ($scope, Data) {
$scope.home_main= '';
$scope.$watch('home_main', function (newValue, oldValue) {
if (newValue !== oldValue) Data.sethome_main(newValue);
});
});
myApp.controller('SecondCtrl', function ($scope, Data) {
$scope.$watch(function () { return Data.gethome_main(); }, function (newValue, oldValue) {
if (newValue !== oldValue) $scope.home_main= newValue;
});
});