所以我有这个自定义指令,您可以在下面看到。

myApp.directive('myDirective', function (testService) {
    return {
        restrict:'EA',
        link:function (scope, element, attr) {
           //defined the object
           var object = new object();
           testService.setObject(object);
    }
   }
});

myApp.directive('mySecondDirective', function (testService) {
    return {
        restrict:'EA',
        link:function (scope, element, attr) {
           //call the variable from previous custom directive
           console.log(testService.getobject()); -> always return undefined
    }
   }
});


这是我在上面使用指令的html结构。

<my-directive></my-directive>

<my-second-directive></my-second-directive>


在那里,我想从以前的自定义指令中检索包含objectnew object(),但是它总是返回一个undefined我想知道如何在不使用require或孤立范围的情况下做到这一点。你们可以帮助我吗?

更新
我创建了一个服务来提供设置和恢复对象的功能,并且显然返回的结果是未定义的,因为我通过这种方式设置了自定义direcitve

<my-second-directive></my-second-directive>

<my-directive></my-directive>


这就是服务

define(
        ['services/services'],
        function(services)
        {
            'use strict';

            services.factory('testService', [function() {
                    var me = this;
                    var testObject = '';

                    return {
                        setObject: function(object) {
                            me.testObject = object;
                        },
                        getObject: function() {
                            return me.testObject;
                        }
                    }
                }
            ]);
        }
);


事实是,我实际上像上面已经提到的那样设置了html标记,这是

<my-second-directive></my-second-directive>

<my-directive></my-directive>


所以您能给我一些建议,我该怎么做吗?

注意*传递的对象实际上有效,我更喜欢使用服务,因为它很容易维护后者。问题是,即使在我在html标记处定义的指令(作为html自身的最后位置)中初始化安装对象(设置对象),也如何使该对象可从另一个指令访问?

更新这是我为您所理解的PLUNKER问题

最佳答案

您可以通过触发自定义事件,然后在第二个指令中侦听它来实现此目的。这是更新的插件:http://plnkr.co/edit/512gi6mfepyc04JKfiep?p=info

从第一个指令广播事件:

app.directive('myDirective', function(testService) {
  return {
    restrict: 'EA',
    link: function(scope, elm, attr) {
      var object = {};
      testService.setObject(object);
      console.log('setting object');
      scope.$broadcast('objectSet');
    }
  }
});


...然后在第二个收听:

app.directive('mySecondDirective', function(testService) {
  return {
    restrict: 'EA',
    link: function(scope, elm, attr) {
      scope.$on('objectSet', function(){
        console.log('retrieving object', testService.getObject());
      })
    }
  }
});


如果您想发出要由第二条指令拾取的特定数据,则还可以将数据与事件一起传递。

09-25 18:23
查看更多