0

I know I shouldn't be using jQuery in combination with Angular, but this is just for the demonstration purposes.

I'm struggling with understanding as to how to inject/insert a directive's attribute inside the controller?

Code:

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

app.controller('MainCtrl', function($scope) {

  $('#myDiv1').html('<p>This works</p>');

  //this below doesn't work when injecting directive attribute
  $('#myDiv2').html('<p my-directive></p>');

})
.directive("myDirective", [function () {
        return {
        restrict: 'EAC',
        require: '?ngModel',
        link: function($scope, element, attrs, controller) {
          var controllerOptions, options;
          element.text('Hello There');
        }
      };
}]);

PLUNKR

Can anyone help please? Is there a way to achieve this?

angular_learner
  • 671
  • 2
  • 14
  • 31
  • maybe it's for demo purposes and you are trying to achieve something greater, but why not just have the directive already in your view? If its a directive that needs to be shown/hidden at certain times, you can use ng-show or ng-if – Ronnie Jul 09 '15 at 19:22
  • 1
    in any case, this solution looks like what you're looking for: http://stackoverflow.com/a/15279343/736967 – Ronnie Jul 09 '15 at 19:27
  • Its working , the plunker your provided , http://plnkr.co/edit/eA3a4FttXd5ahmTVV5le?p=preview isnt it? – Shushanth Pallegar Jul 09 '15 at 19:29

1 Answers1

1

Change your code to following

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

app.controller('MainCtrl', function($scope, $compile) {

  $('#myDiv1').html('<p>This works</p>');

  //this below doesn't work when injecting directive attribute
  $('#myDiv2').html('<p my-directive></p>');
$compile($("#myDiv2"))($scope);

})
.directive("myDirective", [function () {
        return {
        restrict: 'EAC',
        require: '?ngModel',
        link: function($scope, element, attrs, controller) {
          var controllerOptions, options;
          element.text('Hello There');
        }
      };
}]);
dhavalcengg
  • 4,678
  • 1
  • 17
  • 25