How to associate a directive with a controller in HTML?

Suppose I have a CARD directive

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

and the controller say CARDCONTROLLER

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

and the HTML file says CARD.HTML

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

But the above does not work.

Does anyone have any ideas on how to do this?

EDIT. I do not want to generate the directive dynamically. It’s just that I want to bind it through the controller without changing anything in the directive

+4
source share
4 answers

You must add a controller to your directive.

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

this should do the trick.

0
source

call your directive for example

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

.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>  
Hide result
0
source

Source: https://habr.com/ru/post/1653094/


All Articles