javascript - Eval 指令的参数 Angular

标签 javascript angularjs angularjs-directive directive

我有这个 html 模板:

<div width-watcher>
    <div parallax-bg parallax-active="!(tablet || mobile)">
        ...
    </div>
</div>

width-watcher 公开 3 个 bool 值:移动设备、平板电脑和屏幕。这里没有指令选项。我想计算表达式 "!(tablet || mobile)" 将其传递给我的第二个指令 parallax-bg,以禁用移动设备上的视差。

我尝试了以下方法(在parallax-bg中):

  • 使用scope.$eval(attr.parallaxActive)返回“undefined”
  • 直接使用scope.parallaxActive:
    • "&" => 返回一个函数,执行时返回"undefined"
    • "=" => 返回"undefined"
    • "@" => 返回"!(平板电脑 || 移动设备)"

我已经没有主意了。由于英语不是我的母语,我可能错过了 Google 上的一些解决方案。

这是我的背景视差指令的代码:

.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){
            ...
        }
    }
};

最佳答案

您的第一个方法 scope.$eval(attr.parallaxActive) 是正确的,但如果您将属性值绑定(bind)到指令的范围,则该方法将不起作用。

工作示例: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));
  };
}

也就是说,我的建议是使用工厂策略将您的 widthWatcher 指令转变为服务。这样,您就可以将其注入(inject)任何 Controller 、指令、过滤器或其他服务中,并确定屏幕类型,而无需依赖范围。

工作示例: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());
  };
}

更新

为了解决有关调用 parallaxBg 链接函数时未定义值的评论,我更新了 JSFiddle显示调用链接函数的顺序。

为了了解发生了什么,您需要了解 how directives are compiled .

关于javascript - Eval 指令的参数 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35241783/

相关文章:

javascript - angularjs 指令丢失数组格式过滤器

javascript - 在 Ionic AngularJS 中获取未定义的 ngModel

javascript - 将鼠标悬停在图像上并显示该图像的链接

javascript - 间隔一段时间后发送推送通知

angularjs - 将 sw-precache 与客户端 URL 路由一起用于单页应用程序

AngularJS - 如何从链接函数访问隔离范围?

php - 使用 Javascript 更改 Wordpress 中的导航 CSS

javascript - 我们可以加载动态 Angular 对话框吗?

相机的 javascript 操纵杆

javascript - 当值更改时,嵌入自定义指令中的 ng-switch 不会被评估