在控制器中使用angularjs指令属性

时间:2015-07-09 19:18:32

标签: angularjs angularjs-directive

我知道我不应该将jQuery与Angular结合使用,但这只是为了演示目的。

我很难理解如何在控制器中注入/插入指令的属性?

代码:

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

有人可以帮忙吗?有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

将您的代码更改为以下

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');
        }
      };
}]);