在模板中编译动态指令

时间:2015-02-28 14:56:39

标签: angularjs angularjs-directive

我有这样的指示:

foldeskApp.directive('contributionFooter', function() {
    return {
        restrict: 'C',
        template: '<button type="button" class="btn" ng-class="{\'btn-success\': canCreate()}">Add</button>'
    };
});

这样的控制器:

foldeskApp.controller('MainCtrl',
    ['Auth', '$scope', function(Auth, $scope) {
    $scope.footerType = 'contribution';
}]);

我可以像这样调用指令吗?

<div class="modal-footer {{footerType}}-footer"></div>

1 个答案:

答案 0 :(得分:0)

您需要使用$ compile服务编译DOM。

这是一个如何实现这一目标的例子,虽然我不喜欢在这里使用$ timeout:

http://codepen.io/jlowcs/pen/jEKKjZ

HTML:

<div ng-controller="MainCtrl">
  <div class="modal-footer {{footerType}}-footer"></div>
</div>

JS:

angular.module('exampleApp', [])
.directive('contributionFooter', function() {
    return {
        restrict: 'C',
        template: '<button type="button" class="btn" ng-class="{\'btn-success\': canCreate()}">Add</button>'
    };
})
.controller('MainCtrl', function($scope, $element, $timeout, $compile) {
    $scope.footerType = 'contribution';

    //timeout to do it when {{footerType}} has been replaced
    //but it would probably be best to do this in a link function in a directive
    $timeout(function () {
      $compile($element.children())($scope);
    });
});

angular.bootstrap(document, ['exampleApp']);