【问题标题】:how to use angular expression value as an attribute for html element如何使用角度表达式值作为 html 元素的属性
【发布时间】:2016-01-26 20:23:28
【问题描述】:

我有一个场景,我需要在运行时(按钮单击)将不同的指令(属性)应用于 Angular 引导模式内的 DIV。

我会知道要应用的指令的名称。但我无法弄清楚如何在运行时更改模板以将必要的指令名称作为属性添加到 DIV。

考虑一下plunker

基本上我希望 div 使用这样的语法将子指令作为属性 <div {{child}}></div>

所以当它工作时,它应该生成<div child-directive></div>

如何做到这一点?这甚至可能吗?在打开 Modal 之前更改模板以使其在加载时正确连接的最佳方法是什么。

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angular-ui-bootstrap


    【解决方案1】:
    // Code goes here
    
    var app = angular.module('main-module', ['ui.bootstrap']);
    
    app.directive('parentDirective', function($uibModal, $compile) {
        return {
          restrict: 'E',
          template: "<h2>I am Parent</h2><button ng-click='click()'>Click Me</button>",
          scope: {
            child:'@'
          },
          link: function($scope, elem, attrs) {
            console.log('?',$scope.child, $scope);
    
            var template = "<div><h3>This is modal</h3>" 
                  + "Ideally you should see the child directive below"
                  + "<hr />"
                  + "<div "+ $scope.child + "></div></div>"; 
    
            $scope.click = function() {
              $uibModal.open({
                template: template,
                scope: $scope,
                size: 'lg',
              });
            }
          }
        };
      })
      .directive('childDirective', function() {
        return {
          restrict: 'A',
          template: "<div><h4>I am Child</h4><a ng-click='click()'>Click Me!!</a></div>",
          replace: true,
          scope: {},
          link: function($scope, elem, attrs) {
            $scope.click = function() {
              alert("I am in child scope");
            }
          }
        };
      }).directive('anotherChildDirective', function() {
        return {
          restrict: 'A',
          template: "<div><h4>I am another Child</h4><a ng-click='click()'>Click Me!!</a></div>",
          replace: true,
          scope: {},
          link: function($scope, elem, attrs) {
            $scope.click = function() {
              alert("I am in child scope");
            }
          }
        };
      });;
    

    【讨论】:

    • 你能分享一个可以工作的 plunker 吗?我试过你上面说的,它不起作用。我仍然没有在模态中看到子指令
    • 我看到你的 plunker 有硬编码指令。这没有抓住重点。我想在运行时指定指令名称。您已经像这样更改了 modalContent.html。 (
      ) 但我不想那样做。我需要评估范围变量并将该值作为 div 的属性。
    • 好吧,我想明白了,我认为用你的方式注册和执行子指令会有问题
    • 好的,我找到了解决这个问题的方法 :) plunker 在这里准备好了:plnkr.co/edit/Du5tmdjCmJDsmJxeGbhK?p=preview 如果满意,请接受我的回答
    • 根据我上面的问题,在努力以某种方式让它按照我想要的方式工作之后,我最终做了和 Mike86 一样的事情,我不得不使用模板而不是 templateUrl,并在运行时生成模板.因此将此标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2017-11-10
    • 2011-10-26
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多