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?

3
  • 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 Commented Jul 9, 2015 at 19:22
  • 1
    in any case, this solution looks like what you're looking for: stackoverflow.com/a/15279343/736967 Commented Jul 9, 2015 at 19:27
  • Its working , the plunker your provided , plnkr.co/edit/eA3a4FttXd5ahmTVV5le?p=preview isnt it? Commented Jul 9, 2015 at 19:29

1 Answer 1

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');
        }
      };
}]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.