哪里是个好地方,我来声明/初始化我的模块$范围变量? [英] Where is a good place for me to declare / initialize $scope variables for my module?

查看:123
本文介绍了哪里是个好地方,我来声明/初始化我的模块$范围变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

angular.module('admin')
    .controller('AdminContentController',
    ['$scope', '$resource', 'gridService', 'gridSelectService', 'localStorageService', 'utilityService',
    function ($scope, $resource, gridService, gridSelectService, localStorageService, utilityService ) {

        localStorageService.add('ls.adminPage', 'content');
        $scope.entityType = 'Content';
        gridService.gridSetup($scope);

angular.module('admin')
    .factory('gridService',
    ['$resource', '$timeout', 'gridSelectService', 'localStorageService', 'utilityService',
    function ($resource, $timeout, gridSelectService, localStorageService, utilityService) {
        var factory = {
            gridSetup: function ($scope) {
                $scope.grid = {
                    fetching: false,
                    pristine: true,
                    pageType: 'Edit'
                }

我在初始化服务范围的变量,但我不知道这是否是这样做的正确方法。

I am initializing the scope variables in the service but I am not sure if this is the correct way to do this.

有没有为我设置$范围变量在另一个地方的模块?一个更好的办法

Is there a better way for me to set up $scope variables for the module in another place?

推荐答案

是的,它很好的做法变量存储到服务。

Yes, its good practice to store variables into service.

服务是可以注入到任何控制器和一个控制器的范围,暴露自己的价值观单身。

Services are Singletons that you can inject to any controller and expose their values in a controller's scope.

但是,你不能注入 $范围到服务,有什么比一个单身$范围。
您可以实施工厂通过这样的方式:

However, you can't inject $scope into services, there is nothing like a singleton $scope. You can implement factory by this way:

myApp.factory('gridService',
    ['$timeout',
    function ( $timeout) {

        var grid = {
                    fetching: false,
                    pristine: true,
                    pageType: 'Edit'
                }        

       return {
            gridSetup: function () {                
               return grid;
            },
           setGridSetup: function (newGrid) {
               grid = newGrid;
            }
        }
        }]);

和我们用我们的工厂从控制器:

And we use our factory from controller:

$scope.newGrid = gridService.gridSetup();
$scope.copyGrid = angular.copy($scope.newGrid);


$timeout(function() {
   $scope.copyGrid.pageType = "Fess"; 
    gridService.setGridSetup($scope.copyGrid);   
     $scope.newGrid = gridService.gridSetup();
}, 3000);

我们加载了模型,3秒后,我们改变 pageType为何,再存放起来。接下来的负荷后,我们得到改进模型。

We load out model, after 3 sec we change pageType and store it again. after next load we get modified model.

演示<大骨节病> 小提琴

这篇关于哪里是个好地方,我来声明/初始化我的模块$范围变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆