如何在控制器和指令之间共享服务动态数据 [英] How share Service dynamic data between Controllers and Directives

查看:22
本文介绍了如何在控制器和指令之间共享服务动态数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用什么模式,如果我需要我的服务在控制器、指令等之间共享它的动态数据.我提到动态的原因是因为我想加载新数据和这些数据需要在任何其他控制器、指令等中可用.例如,如果指令生成 UL LI,如果服务内部的数据发生变化,则必须重新生成它!

I'd like to know what pattern to use, if I need my Service to share it's dynamic data between Controller, Directives, etc. The reason I mention dynamic, is because I'd like to load new data and this data needs to be available in any other Controller, Directive, etc. For example, if a Directive generates a UL LI, it would have to re-generate it if the data inside the Service has changed!

我最初打开了以下(How在服务中创建 reset() 方法返回承诺? ),有人指出我应该使用观察者模式.我非常感激,我很快就写了这篇文章,因为我需要做的事情和评论将非常感谢(http://jsbin.com/epAMaP/1 )

I've initially opened the following ( How to create reset() method in Service that return promise? ) and someone pointed to me that I should use the Observer Pattern. Which I'm very grateful and I wrote this very quickly as a spike of what I need to do and comments would be extremely appreciated ( http://jsbin.com/epAMaP/1 )

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

MyApp.config(function($locationProvider){

  $locationProvider.hashPrefix('!');

});

MyApp.factory('MyService', function($timeout){

    var data;

    var loadData = function(){

        data = {
            foo: "bar",
            time: new Date()
        };

        return data;

    };

    return {

        refresh: function(){

            loadData();

        },

        getData: function(){

            return loadData();

        }

    };

});

MyApp.controller('MyCtrl', function($scope,MyService,$timeout){

  $scope.foo = "Service share data";

  $scope.data = MyService.getData();

  $scope.$on("eventFoo", function(){
    console.log("Data has changed!");
    console.log($scope.data);
  });

  $timeout(function(){
    MyService.refresh();
    $scope.$apply(function(){
        $scope.data = MyService.getData();

        $scope.$emit("eventFoo");
    });
  }, 3000);

});

MyApp.directive('myDirective', function(MyService,$timeout){

    return {
        restrict: 'A',
        link: function(scope, elem, attrs){
            scope.$on("eventFoo", function(){
                console.log("Event foo triggered!");

                scope.data = MyService.getData();

                console.log(scope.data);
            });
        }
    };

});

我认为这可以解决我的大部分问题,但我需要记住一些事情.我要加载的数据来自$http GET,所以我认为每次需要更新或加载数据时至少需要使用一个promise,然后触发正确的事件.

I think this would solve most of my problems but there's something that I need to remember. The data that I'll load comes from $http GET, so I think that I need to use at least a promise every time I need to update or load data, then trigger the right event.

我对 AngularJs 缺乏经验使我怀疑自己的想法,因此非常感谢任何帮助或建议!

My lack of experience with AngularJs drive me into question my thoughts, so any help or advice is extremely appreciated!

感谢您的关注!

推荐答案

我想我找到了一个可能的答案,使用 promise 和观察者模式(如果这是正确的并描述了我在做什么):

I think I found a possible answer, using promise and the Observer Pattern (if this is correct and describes what I'm doing):

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

MyApp.config(function($locationProvider){

  $locationProvider.hashPrefix('!');

});

MyApp.factory('MyService', function($q,$timeout,$rootScope){
    
    var deferred;
    var data;

    var loadData = function(){

        data = {
            foo: "bar" +  Math.floor((Math.random()*100)+1),
            time: new Date()
        };

        deferred.resolve(data);

    };

    return {

        getPromise: function(){

            deferred = $q.defer();
            loadData();

            return deferred.promise;

        },

        getData: function(){
            
            return data;

        }

    };

});

MyApp.controller('MyCtrl', function($scope,MyService,$timeout){
    
  $scope.foo = "Service share data";
 
  MyService.getPromise().then(function(data){
    $scope.data = data;
    console.log("Initial data request:");
    console.log($scope.data);
    $scope.$emit("eventFoo");
  });

  // then after awhile a user requests updated data
  $timeout(function(){

    console.log("// then after awhile a user requests updated data");

    $scope.$apply(function(){

        MyService.getPromise().then(function(data){

            $scope.data = MyService.getData();
            $scope.$emit("eventFoo");

        });         

    });
  }, 3000);

});

MyApp.directive('myDirective', function(MyService,$timeout){

    return {
        restrict: 'A',
        link: function(scope, elem, attrs){
            scope.$on("eventFoo", function(){
                console.log("Event foo triggered!");

                scope.data = MyService.getData();

                console.log(scope.data);
            });
        }
    };

});

您可以在 http://jsbin.com/ahiYiBu/1/

这篇关于如何在控制器和指令之间共享服务动态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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