can控制器可以在Angular的$ rootScope中创建任意属性

时间:2014-09-09 19:05:47

标签: angularjs rootscope

控制器在Angular中执行类似的操作是否合法?

       $rootScope.someArbitaryObject = ["fee", "fie", "fo", "fum];

      $rootScope.foo = {name: "Jane Q. Public", favoriteColor: "green"}

2 个答案:

答案 0 :(得分:0)

关于评论中的问题,分享日期的好方法是通过localstorage(或sessionStorage)。我写了一个storageService,它允许你保存,加载和删除。

angular.module(yourApplication).service('storageService', [
    function() {

        // implementation using localStorage. Future possibility to user $cookie service here, or sessionStorage, depends on what you want
        return {
            save: function(key, jsonData, expirationMin){ // default is 30 minute expiration
                if(!expirationMin)
                    expirationMin = 30;
                var expirationMS = expirationMin * 60 * 1000;
                var record = {
                    value: JSON.stringify(jsonData), 
                    timestamp: new Date().getTime() + expirationMS
                };
                localStorage.setItem(key, JSON.stringify(record));
                return jsonData;
            }, 
            load: function(key){
                var record = JSON.parse(localStorage.getItem(key));
                if (!record){ 
                    return false; 
                }
                return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
            },
            remove: function(key){
                localStorage.removeItem(key);
            }
        };
    }
]);

使用服务的另一种方式(修改了Yoni&#39;代码):

var myApp = angular.module('myApp', []);

myApp.service('MyService', function () {
    var someData = 'test';
    return { 
        getData: function(){ return someData},
        setData: function(input){ someData = input;}
    };
});

myApp.controller('FirstCtrl', function($scope, MyService) {
    $scope.data = MyService.getData();
});

myApp.controller('SecondCtrl', function($scope, MyService) {
    $scope.data = MyService.getData;
});

答案 1 :(得分:0)

是的,这是合法的,但前提是您希望所有控制器都能访问该模型。

更好的做法是使用可以注入一个或多个控制器的服务:

var myApp = angular.module('myApp', []);

myApp.factory('MyService', function () {
  return { message: "I'm data from a service" };
});

myApp.controller('FirstCtrl', function($scope, MyService) {
  $scope.data = MyService;
});

myApp.controller('SecondCtrl', function($scope, MyService) {
  $scope.data = MyService;
});

您在一个控制器中对MyService属性所做的任何更改都将影响使用MyService的所有其他控制器。