Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在模板内编译动态指令_Angularjs_Angularjs Directive - Fatal编程技术网

Angularjs 在模板内编译动态指令

Angularjs 在模板内编译动态指令,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我有这样的指示: foldeskApp.directive('contributionFooter', function() { return { restrict: 'C', template: '<button type="button" class="btn" ng-class="{\'btn-success\': canCreate()}">Add</button>' }; }); foldeskApp.contr

我有这样的指示:

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>

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

下面是一个如何实现这一点的示例,尽管我不喜欢在这里使用$timeout:

HTML:

JS:


代码对我来说似乎很好。。。你在运行它时遇到过什么问题吗?我敢肯定你不会。Angular会在DOM插值对象之前编译DOMexpressions@LinhPham它根本不编译它……这不起作用,原因是@NewDev states。需要在HTML中严格定义要编译的指令。不能将变量用于其他任何地方的指令,基于类的指令也不例外。如果该值发生变化,则需要重新编译该元素,而这正是Angular为您所做的。最好的办法是使用ng include和使用转换的不同模板。因此,我建议为该模式页脚标记创建一个指令,以便您可以在其链接函数内执行编译调用。
<div ng-controller="MainCtrl">
  <div class="modal-footer {{footerType}}-footer"></div>
</div>
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']);