应用程序生命周期内创建的对象中的指令不起作用

时间:2016-01-29 17:22:13

标签: javascript angularjs

我已经创建了一些基本指令。如果我将它与html文件中的某些对象一起使用,它的效果很好

<some-directive some-data="123"></some-directive>

但是,如果我将此对象动态加载到我的网页:

//getting html source as a string, then appending it to DOM:
elem.html("<some-directive some-data='123'></some-directive>");

该指令不起作用(将对象正确添加到DOM)

app.directive('someDirective', function (notes, parts) {
return {
    restrict: 'AE',
    scope: {
        someData: '='
    },
    link: function (scope, elem, attrs) {
        console.log("directive fired");
    }
};
});

如何才能使其正常运作?

1 个答案:

答案 0 :(得分:1)

对于动态指令,您必须使用将范围编译为模板的$compile服务。查看下面的示例,<some-directive-wrapper /><some-directive />元素添加到自身并编译范围值

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

app.directive('someDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            someData: '='
        },
        template: '<h2>someDirective compiled, someData is {{someData}}</h2>',
        link: function (scope, elem, attrs) {
            console.log("directive fired");
        }
    };
});
app.directive('someDirectiveWrapper', function ($compile) {
    return {
        restrict: 'AE',
        link: function (scope, elem, attrs) {
          
          //get value from ajax maybe
          //and set to scope
          scope.data = 123;

          //replace directive with another directive
          elem.html('<h1>someDirectiveWrapper compiled </h1>\n<some-directive some-data="data"></some-directive>');

          //compile scope value into template
          $compile(elem.contents())(scope);
        }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <some-directive-wrapper></some-directive-wrapper>
</div>