【问题标题】:Change of select should take effect to all other select elements and vice versa选择的更改应该对所有其他选择元素生效,反之亦然
【发布时间】:2015-09-17 08:36:20
【问题描述】:

我创建了一个指令并在同一页面上使用了两次。但是它们被放入另一个指令中

<directive1>
    <select-directive/>
</directive1>

<directive1>
    <select-directive/>
</directive1>

现在更改其中一个选择的值也应该对另一个选择元素生效。

这可能吗?

编辑

尝试将 $rootScope 与 $broadcast 和 $on 一起使用。但是当从第一个选择字段中选择一个值时,第二个被设置为“空”,就像没有选择任何内容一样。现在从 secong 中选择一些值会导致第一个选择字段为空。

(function() {
'use strict';

var currencySelectionBox = function(ServiceFactory, $rootScope) {
    return {
        restrict: "E",
        replace: true,
        scope: false,
        template: '<select ng-options="o.currency_code for o in currencyList" ng-model="currencyListSelectedValue" class="form-control"></select>',
        link: function(scope, element, attrs) {
            ServiceFactory.getCurrencies().then(function(response) {
                scope.currencyList = response.data.items;
            });

            element.bind("change", function(e) {
                $rootScope.$broadcast('currencyChanged', scope.currencyListSelectedValue);
            });

            $rootScope.$on('currencyChanged', function(event, data) {
                scope.currencyListSelectedValue = data;
                console.log(scope.currencyListSelectedValue);

            });

        }
    };
};

angular
    .module('app')
    .directive('currencySelectionBox', ['ServiceFactory', '$rootScope', currencySelectionBox]);
})();

【问题讨论】:

    标签: angularjs angular-directive


    【解决方案1】:

    是的,这是可能的。

    您可以使用$rootScope 作为指令之间的通信渠道。这些指令很可能具有孤立的范围,并且无法相互通信。所以你使用$rootScope.$broadcast('eventName')$rootScope.$emit('eventName') 来通知其他指令一些事件。

    然后你的指令用$rootScope.$on('eventName', function(event, args){})监听

    您可能希望在每个指令实例中设置唯一 ID,然后也广播此 ID,以便您可以区分事件的来源。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-02
      • 2014-04-05
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      相关资源
      最近更新 更多