2

와 transclude를 사용하여 나는 다음과 같은 설정이 있습니다각도 : NG-바인드 HTML

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

app.filter('unsafe', function($sce) { 
    return $sce.trustAsHtml; 
}); 

app.controller('SearchController', ['$scope', '$http', function($scope, $http) { 
    $scope.searchString = ''; 
    $scope.searchType = 'Artist'; 
    $scope.updateHtml = function() { 
    $http.get('/search', { 
     params: { 
     searchString: $scope.searchString, 
     searchType: $scope.searchType 
     } 
    }).success(function(data) { 
     $scope.html = data; 
    }).error(function(err){ 
     $scope.html = err; 
    }); 
    }; 
    $scope.updateHtml(); 
}]); 

app.directive('searchDirective', function() { 
    return { 
    restrict: 'A', 
    transclude: true, 
    template: '<div ng-bind-html="html | unsafe" ng-transclude></div>' 
    }; 
}); 

그것을 @scope.html에서 컨트롤러와 상점에서 아약스를 통해 원시 HTML 태그를 가져옵니다을. 지시문에서이 html은 ng-bind-html을 통해 DOM에 삽입됩니다. 그것은 기본적으로 작동

#search(ng-controller="SearchController" search-directive) 

을 다음과 같이

HTML (옥)가 보인다. 하지만 포함 된이 html 안에는 내가 풀리고 싶은 {{searchType}}과 같은 독점적 인 콘텐츠가 있습니다. 불행히도, 그 경우가 아니라 브라우저에 "{{searchType}}"이 표시됩니다. 출제 작업을하기 위해 무엇을 변경할 수 있습니까?

$compile$transclude을 읽었지 만 사용 방법을 모르거나 내 문제를 해결하는 데 도움이되는지 확인합니다. 고마워!

+1

컨트롤러에서 $ scope.html로 설정하기 전에 html을 $ interpolate하십시오. 이 질문에 대한 답변보기 : http://stackoverflow.com/questions/20796102/angularjs-data-bind-in-ng-bind-html – Patrick

+0

위대한, $ interpolate가 트릭을 수행합니다! 고맙습니다! – Hinrich

답변

2

패트릭의 도움으로 나는 그것을 풀 수 있었다. 내 컨트롤러를

app.controller('SearchController', ['$scope', '$http', '$interpolate', 
       function($scope, $http, $interpolate) { 
    $scope.searchString = ''; 
    $scope.searchType = 'Artist'; 
    $scope.updateHtml = function() { 
     $http.get('/search', { 
     params: { 
      searchString: $scope.searchString, 
      searchType: $scope.searchType 
     } 
     }).success(function(data) { 
     $scope.html = $interpolate(data)($scope); // <<-- difference here 
     }).error(function(err){ 
     $scope.html = err; 
     }); 
    }; 
    $scope.updateHtml(); 
    }]); 

으로 변경했습니다. 이제 내 html은 전달 범위에 따라 보간됩니다. 고맙습니다!

편집 : $interpolate은 DOM을 렌더링하고 범위를 통해 구문 분석하기위한 것입니다. 단순히 일반 HTML을 반환합니다. 각도 코드가 포함 된 완전한 작업 HTML 템플릿을 실제로 가져와야하는 경우 $compile을 사용하십시오. 나는 this answer$interpolate, $compile$parse 사이의 차이를 분류하는 데 매우 유용하다는 것을 알았습니다.