角度指令间通信

时间:2014-07-10 11:12:55

标签: javascript jquery angularjs

我用几个指令创建了以下简单代码(我有几个月的Angular经验)。

我使用了不寻常的方式来进行一些基本的继承(正如你可以从Directive类中看到的),默认情况下参数(使用||),将一个元素插入另一个元素的可能性(使用transclude),添加了特定于目录的控制器当然还指定了链接函数以支持DOM事件处理程序。

目前我正在尝试通过它的范围调用另一个目录控制器中指定的函数,但它失败了。错误是'Uncaught TypeError:undefined不是函数'。

我的目标是独立于DOM结构调用控制器的功能(目标元素可以是兄弟,父或子)。我也考虑过共享服务和广播事件,但似乎不是进行通信的正确方法。

为什么代码无法正常运行? 还有其他方法可以做到吗?

提前致谢。

HTML

<body ng-app="app">
    <component id="button" name="button">
    </component>
    <icon name="icon">
    </icon>
</body>

JS

(function() {
    var app = angular.module('app', []);

    app.directive('icon', function() {
        var directive = new Directive();
        return directive;
    });

    app.directive('button', function() {
        var directive = new Directive();
        return directive;
    });

    function Directive(options) {
        options = options || {};
        this.scope = options.scope || {
            name: '@'
        };
        this.restrict = options.restrict || 'E';
        this.replace = (options.replace != null) ? options.replace : true;
        this.transclude = (options.transclude != null) ? options.transclude : true;
        this.template = options.template || '<div ng-transclude></div>';
        this.controller = function($scope) {
            $scope.focus = function() {
                console.log('focus');
            };
            $scope.outFocus = function() {
                console.log('outFocus');
            };
        };
        this.link = options.link || function($scope, $element, $attrs) {
            $element.click(function() {
                $scope.focus();
                var _scope = angular.element('#button').scope();
                _scope.outFocus(); // doesn't work
            });
        };
    }
})();

0 个答案:

没有答案