javascript - Eval directive's parameters angular -
i have html template :
<div width-watcher> <div parallax-bg parallax-active="!(tablet || mobile)"> ... </div> </div> width-watcher exposes 3 boolean values: mobile, tablet , screen. no directive options here. want evaluate expression "!(tablet || mobile)" pass second directive parallax-bg, disable parallax on mobile devices.
i've tried following (in parallax-bg):
- use
scope.$eval(attr.parallaxactive)returns"undefined" - use directly scope.parallaxactive :
"&"=> returns function, when executed returns"undefined""="=> returns"undefined""@"=> returns"!(tablet || mobile)"
and ran out of ideas. english isn't native language, i've missed solutions on google.
this code of background-parallax directive :
.directive('parallaxbackground', function($window) { return { transclude: true, template: '<div ng-transclude></div>', scope: { parallaxratio: '@', parallaxoffset: '@', }, link: function(scope, elem, attrs) { var scopeactive = scope.$eval(attrs.parallaxactive); var ... if(scopeactive){ ... } } };
your first method, scope.$eval(attr.parallaxactive) correct, won't work if bind attribute value directive's scope.
working example: jsfiddle
angular.module('myapp').directive(function() { return { link: postlink, template: '<ng-transclude></ng-transclude>', transclude: true }; function postlink(scope, ielement, iattrs) { alert(scope.$eval(iattrs.parallaxactive)); }; } that said, recommendation turn widthwatcher directive service using factory strategy. way, can inject controller, directive, filter or other service , determine screen type without relying on scope.
working example: jsfiddle
angular.module('myapp', []) .factory('$widthwatcher', widthwatcherfactory) .directive('parallaxbg', parallaxbgdirective) ; function widthwatcherfactory() { return { ismobile: ismobile, isscreen: isscreen, istablet: istablet }; function getwidth() { return window.innerwidth || document.body.clientwidth; } function ismobile() { return getwidth() < 600; } function isscreen() { return getwidth() > 960; } function istablet() { return !ismobile() && !isscreen(); } } function parallaxbgdirective($widthwatcher) { return { link: postlink, template: '<ng-transclude></ng-transclude>', transclude: true }; function postlink(scope, ielement, iattrs) { alert($widthwatcher.isscreen()); }; } update
to address comment values being undefined when parallaxbg link function called, updated jsfiddle show order in link functions called.
in order understand going on, need understand how directives compiled.
Comments
Post a Comment