0

ディレクティブテンプレートでディレクティブスコープを使用しました。 私は以前に格納されたテンプレートキャッシュからhtmlを取得しようとしました。Angularjs - スコープの値がテンプレートに適用されていません

しかし、現在の指令スコープは指令には適用されません。私は理由は何ではない。

私はテンプレートをコンパイルして値を取得しようとしました。しかし、適用されません。

contentString = $templateCache.get('template/MyTemplate') 

var div = document.createElement("div"); 
div = angular.element(div).html(contentString); 
var s = $compile(div.contents())($scope); 

テンプレート/ MyTemplateには、次のような

<div> 
    {{obj.value}} 
</div> 

指令範囲以下になる

私は

<div class="ng-scope"> 
    {{obj.value}} 
</div> 

のような出力がどのような問題になりました

link: function ($scope, $element, $attributes) { 
    $scope.obj.value="This is my test" 
} 

答えて

1

隔離されたスコープを持つカスタムディレクティブを使用しているこの例を確認してください。以下の例があなたに役立つことを願っています。

angular 
 
    .module('demo', []) 
 
    .directive('hello', hello); 
 
    
 
    hello.$inject = ['$templateCache', '$compile']; 
 
    
 
    function hello($templateCache, $compile) { 
 
    var directive = { 
 
     scope: { 
 
     }, 
 
     link: linkFunc 
 
    }; 
 
    
 
    return directive; 
 
    
 
    function linkFunc(scope, element, attrs, ngModelCtrl) { 
 
     scope.obj = { 
 
     value: 'Hello, World!' 
 
     }; 
 
     
 
     var template = $templateCache.get('templateId.html'); 
 
     element.html(template); 
 
     $compile(element.contents())(scope); 
 
    } 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> 
 
<div ng-app="demo"> 
 
    <hello></hello> 
 
    <script type="text/ng-template" id="templateId.html"> 
 
    <div> 
 
     {{obj.value}} 
 
    </div> 
 
    </script> 
 
</div>

別の例図とコントローラペア

angular 
 
    .module('demo', []) 
 
    .controller('DefaultController', DefaultController) 
 
    .directive('hello', hello); 
 
    
 
    function DefaultController() { 
 
    var vm = this; 
 
    vm.message = 'Hello, World!'; 
 
    } 
 
    
 
    hello.$inject = ['$templateCache', '$compile']; 
 
    
 
    function hello($templateCache, $compile) { 
 
    var directive = { 
 
     link: linkFunc, 
 
     scope: { 
 
     message: '=' 
 
     }, 
 
     controller: HelloController, 
 
     controllerAs: 'vm', 
 
     bindToController: true 
 
    }; 
 
    
 
    return directive; 
 
    
 
    function linkFunc(scope, element, attrs, ngModelCtrl) { 
 
     var template = $templateCache.get('templateId.html'); 
 
     element.html(template); 
 
     $compile(element.contents())(scope); 
 
    } 
 
    } 
 
    
 
    function HelloController() { 
 
    var vm = this; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script> 
 
<div ng-app="demo"> 
 
    <div ng-controller="DefaultController as ctrl"> 
 
    <hello message="ctrl.message"></hello> 
 
    <script type="text/ng-template" id="templateId.html"> 
 
    \t <p>{{vm.message}}</p> 
 
    \t </script> 
 
    </div> 
 
</div>

controller asを使用と一致するように指示して、即ち controller asをコントローラエイリアシング構文を使用して
関連する問題