2016-08-31 50 views
4

假設我有一個指令CARD如何將控制器中的指令綁定到HTML中?

.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> 

但以上沒有工作。

有沒有人有關於如何做到這一點的任何想法?

編輯。 我不想動態生成指令。它只是我想通過控制器綁定它,而無需更改指令中的任何內容

+2

這裏是一個類似的問題[在角動態代碼生成](http://stackoverflow.com/questions/27574333/dynamic-tag-generation-in-angular)。 –

回答

0

您必須將控制器添加到您的指令中。

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

這應該是訣竅。

0

打電話給你的指令一樣,

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

您可以在指令定義控制器還

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


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

看到下面的代碼片段,你會得到的想法你如何能做到這一點。

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>

相關問題