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(模板);
});代码>
这里有一个类似的问题。