【问题标题】:How to bind a directive from the Controller into the HTML?如何将控制器中的指令绑定到 HTML 中?
【发布时间】:2017-01-07 14:58:22
【问题描述】:

假设我有一个指令CARD

.directive('card', [function() {
  return {
      restrict: 'E', // Element directive,
      templateUrl: 'scripts/directives/card.html'
  };

控制器说 CARDCONTROLLER

.controller('cardController',function($scope){
 $scope.directivename = 'card';
});

和一个 HTML 文件说 CARD.HTML

<div>
 <{{directivename}}></{{directivename}}>
</div>

但是上面的不行。

有没有人知道如何做到这一点?

编辑。 我不想动态生成指令。只是我想通过控制器绑定它而不/更改指令中的任何内容

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

请参阅下面的 sn-p ,您将了解如何做到这一点。

var app = angular.module('myapp',[]);


app.directive('card',function() {
  return {
      restrict: 'E', // Element directive,
      template: '<h5>I am directive template</h5>'
  };
  });


app.controller('cardController',function($scope,$compile,$element){
$scope.directivename = 'card';
  
  var template = $compile("<"+$scope.directivename+"/>")($scope);
  
  $element.append(template);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myapp" ng-controller="cardController">
  
</div>  

【讨论】:

    【解决方案2】:

    您也可以在指令中定义控制器

    .directive('myDirective', function() {
    return {
    restrict: 'E',
    templateUrl: 'scripts/directives/card.html',
    controller: function($scope) {
      //write your controller code here
    
    
    },
    controllerAs: 'myController'
    };
    });
    

    【讨论】:

      【解决方案3】:

      调用你的指令,

      <div>
        <data-card>
          // add code 
        </data-card>
      </div>
      

      【讨论】:

        【解决方案4】:

        您必须将控制器添加到您的指令中。

        .directive('card', function() {
          return {
              restrict: 'E', // Element directive,
              templateUrl: 'scripts/directives/card.html',
              controller: 'cardController'
          }
        })
        

        这应该可以解决问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-12
          • 1970-01-01
          • 1970-01-01
          • 2016-10-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多