2

我正在使用 angular js 并且有一个看起来像这样的控制器

myApp = angular.module("myApp.controllers", []);
myApp.controller("ScheduleCtrl", function($scope, $http, ScheduleService){
    $scope.hours = 4;
    ScheduleService.test();
    ScheduleService.initializeSchedule();
});

和一个看起来像这样的服务(在另一个文件中)

myApp = angular.module('myApp.services', []);
myApp.factory('ScheduleService', ['$rootScope', function($rootScope){

    return {
        test : 
            function(){
                alert("Test");
            },
        initializeSchedule : 
            function(){
                alert($rootScope.hours);
            }
    };
});

为了确保每个人都正确地从服务连接到控制器,在我的控制器内部对“test()”的第一次调用会在警报框中产生所需的输出。但是,对于下一个功能,现在应该警告“4”,而不是警告“未定义”。

我如何使用 $rootScope 或其他东西来将范围变量用于我的服务。

4

3 回答 3

4

您需要注入$rootScope控制器并使用$rootScope而不是$scope. DEMO

myApp.controller("ScheduleCtrl", function($scope, $rootScope, $http, ScheduleService){
    $rootScope.hours = 4;
    ScheduleService.test();
    ScheduleService.initializeSchedule();
});

但在这种情况下,您不需要使用$rootScope.您可以将数据作为参数传递给服务函数。

return {
    test : 
        function(){
            alert("Test");
        },
    initializeSchedule : 
        function(hours){
            alert(hours);
        }
};
于 2014-08-23T02:39:52.230 回答
2

如何在控制器和视图中使用 Angular $rootScope

要跨应用控制器共享全局属性,您可以使用 Angular $rootScope。这是共享数据的另一种选择。

跨控制器共享通用功能的首选方式是服务,读取或更改可以使用 $rootscope 的全局属性。

所有其他作用域都是根作用域的后代作用域,因此请明智地使用 $rootScope。

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);

在模板中使用 $rootScope(使用 $root 访问属性):

<div ng-controller="Ctrl1">
    <div class="banner" ng-show="$root.showBanner"> </div>
</div>
于 2014-09-15T07:38:18.813 回答
0

问题是 $scope 是为您的控制器创建的隔离范围。如果您希望它显示在您的服务中,您需要将 $rootScope 注入您的控制器并修改其小时数。

在此处查看有关范围层次结构的更多信息

控制器:

angular.module('myApp', []).controller('ExampleController', ['$scope', '$rootScope', 'ScheduleService', function($scope, $rootScope, ScheduleService) {
  $scope.hours = 4;
  $rootScope.hours = 42;
  ScheduleService.test();
  ScheduleService.initializeSchedule();
}]);

服务:

angular.module('myApp')
.factory('ScheduleService', function($rootScope) {
  return {
        test : 
            function(){
                alert("Test");
            },
        initializeSchedule : 
            function(childScopeHours){
                alert($rootScope.hours);
            }
    };
});

工作plnkr。

于 2014-08-23T03:16:09.897 回答