指令的角度广播

时间:2015-06-19 18:23:21

标签: javascript angularjs angularjs-directive broadcast angular-ng-if

我试图在点击“声明点数”按钮时从一个指令(声明点)广播到另一个指令(横幅点)。

<button name="button" claim-points>Claim Points</button>

我想隐藏这个“横幅按钮”元素,直到广告从claim-points指令发送到banner-points指令:

<div name="bannerBtn" banner-points ng-if="isVisible">html from banner-points directive displayed here</div>

因此,在“声明点数”按钮上单击,它会获取并循环显示某些数据...如果找到匹配项,则会广播到showbanner

angular
    .module('myApp')
    .directive('claimPoints', ['$rootScope', '$http', function ($rootScope, $http) {
        return {
            restrict: 'AE',
            link: function (scope, elem, attr) {
                elem.bind('click', function() {
                    $http.get('/testJSON/points.json').success(function(data) {
                            var found = false;
                            angular.forEach(data.data, function(v, k) {
                                if (!found) {
                                    if (v.award_name === attr.award) {
                                        found = true;
                                        $rootScope.$broadcast('showbanner', v.points);
                                    }
                                }
                            }
                        );
                    });
                });
            }
        };
    }
]);

广播应该发送到按钮上的scope.$on('showbanner,... here and set the "Banner Button" attribute isVisible to true... which should trigger the ng-if`。

angular
    .module('myApp')
    .directive('bannerPoints', function () {
        return {
            restrict: '',
            templateUrl: '<div>some html I want to display',
            link: function (scope, elem, attr) {
                attr.isVisible = false;
                scope.$on('showbanner', function(e, b) {
                    attr.isVisible = true;
                });
            }
        };
});

广播没有发生。

1 个答案:

答案 0 :(得分:1)

没有必要创建具有bannerPoints侦听器的$on,因为您的指令不是创建隔离范围,您只需要将isVisible范围变量名称传递给{{1然后指令而不是广播你可以直接使用范围[attrs.isVisible]&amp;将其设为真,这样claimPoints就会得到满足,并且该按钮会显示出来。

<强>标记

ng-if="isVisible"

<强>指令

<button name="button" claim-points is-visible="isVisible">Claim Points</button>

<button name="bannerBtn" ng-if="isVisible">
    <div>some html I want to display></div>
</button>