Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将控制器中的指令绑定到HTML中?_Javascript_Angularjs_Angularjs Directive - Fatal编程技术网

Javascript 如何将控制器中的指令绑定到HTML中?

Javascript 如何将控制器中的指令绑定到HTML中?,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,假设我有一张指令卡 .directive('card', [function() { return { restrict: 'E', // Element directive, templateUrl: 'scripts/directives/card.html' }; 一个控制器说CARDCONTROLLER .controller('cardController',function($scope){ $scope.directivename = '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>

但上述方法不起作用

有人知道如何做到这一点吗

编辑。
我不想动态生成指令。我只是想通过控制器绑定指令,而不改变指令中的任何内容。您必须将控制器添加到指令中

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

这应该可以解决问题。

像这样调用您的指令

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

//添加代码

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

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


},
controllerAs: 'myController'
};
});

请参阅下面的代码片段,您将了解如何做到这一点

var-app=angular.module('myapp',[]);
应用程序指令('卡',函数(){
返回{
restrict:'E',//元素指令,
模板:“我是指令模板”
};
});
app.controller('cardController',函数($scope,$compile,$element){
$scope.directivename='card';
变量模板=$compile(“”)($scope);
$element.append(模板);
});

这里有一个类似的问题。