如何使用角度表达式值作为html元素的属性

时间:2016-01-22 11:37:27

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

我有一个场景,我需要在运行时(按钮点击)将角度引导模态中的不同指令(属性)应用于DIV。

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

考虑这个plunker

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

因此,当它起作用时,它应该生成<div child-directive></div>

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

1 个答案:

答案 0 :(得分: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");
        }
      }
    };
  });;