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>
제어기 에일리어싱 구문 즉 지시문 controller as 조회 및 제어와 짝 controller as를 사용과 일치하도록

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>

관련 문제