javascript - angular broadcast from directive -
i trying broadcast 1 directive (claim-points) directive (banner-points) on click of claim points button.
<button name="button" claim-points>claim points</button>
i'd hide "banner button" element until broadcast sent claim-points directive banner-points directive:
<div name="bannerbtn" banner-points ng-if="isvisible">html banner-points directive displayed here</div>
so, on claim points button click, it's getting , looping through data... if finds match, broadcasts 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); } } } ); }); }); } }; } ]);
the broadcast should sent scope.$on('showbanner
, ...here , set "banner button" attribute
isvisibleto true... should trigger the
ng-if` on button.
angular .module('myapp') .directive('bannerpoints', function () { return { restrict: '', templateurl: '<div>some html want display', link: function (scope, elem, attr) { attr.isvisible = false; scope.$on('showbanner', function(e, b) { attr.isvisible = true; }); } }; });
the broadcast not happening.
there no need create bannerpoints
have $on
listener, directive not creating isolated scope, need pass isvisible
scope variable name claimpoints
directive instead of broadcasting directly use scope[attrs.isvisible] & make true ng-if="isvisible"
gets satisfied , button shown.
markup
<button name="button" claim-points is-visible="isvisible">claim points</button> <button name="bannerbtn" ng-if="isvisible"> <div>some html want display></div> </button>
directive
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 set isvisible scope true scope[attrs.isvisible] = true; } } }); }); }); } }; }]);
Comments
Post a Comment