2016-01-29 20 views
0

我已經創建了一些基本指令。它工作得很好,如果我用它在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"); 
    } 
}; 
}); 

我能做些什麼才能使它正常工作?

+2

不會不使用'$ compile'工作...不知道它在那裏編譯 – charlietfl

回答

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>

如果你注入它自己的角度
+0

似乎只有當我點擊它時,它纔會更新它的角度「{{variables}}」。如果我不專注於這種方式創建的對象,它不更新其視圖(腳本正常工作,我用setInterval來檢查它) – Piotrek

+0

你知道如何解決它嗎? – Piotrek

+0

我建議你開一個新的問題,因爲它可能是完全不同的案例研究 –

相關問題