我试图通过单击“声明点”按钮从一个指令(声明点)广播到另一指令(横幅点)。
<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 并将“Banner Button”属性
isVisible设置为 true。 ..这应该触发按钮上的
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;
});
}
};
});
广播没有发生。
最佳答案
无需创建具有 $on
监听器的 bannerPoints
,因为您的指令没有创建隔离范围,您只需传递 isVisible
范围变量名称到 claimPoints
指令,然后您可以直接使用scope[attrs.isVisible] 并将其设为 true,而不是广播,因此 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>
指令
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;
//this will set isVisible scope to true
scope[attrs.isVisible] = true;
}
}
});
});
});
}
};
}]);
关于javascript - 来自指令的 Angular 广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30944884/