angular 将作用域数据绑定到 templateCache

angular bind scope data to templateCache

我的控制器中有这个功能,它加载到模板中

$http.get('scripts/routes/template.html', { cache : $templateCache})
    .then(function(val){
        var returnedTemplate = val.data; // returns string
        $scope.name = 'blah blah';
        $scope.message = 'Good day';
    });

它由val.data加载的模板,是一个字符串

<h3 class="md-title">{{name}}</h3>
<p class="md-title">{{message}}</p>

如何获取从加载的模板返回的字符串并将作用域变量绑定到该字符串?

我需要的结果是

<h3 class="md-title">blah blah</h3>
<p class="md-title">Good day</p>

我曾尝试使用 $compile 函数将数据绑定到字符串,但无济于事。

在此先感谢您的帮助

绑定后需要手动编译html。创建这样的指令。

.directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});

然后在 html 中调用它并将 html 字符串绑定到指令

<div dynamic="returnedTemplate"></div>

控制器

$scope.name = 'blah blah';
 $scope.message = 'Good day';
 $scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'

演示

angular.module("app",[])
.controller("ctrl",function($scope){

        $scope.name = 'blah blah';
        $scope.message = 'Good day';
 $scope.returnedTemplate = '<h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p>'
}).directive('dynamic', function ($compile) {
  return {
    restrict: 'A',
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        ele.html(html);
        $compile(ele.contents())(scope);
      });
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div dynamic="returnedTemplate"></div>
</div>

谢谢,您为我指明了正确的方向,这是最适合我的设置的解决方案。

angular.module("app",[])
.controller("ctrl",function($scope, $compile, $timeout){
        $scope.name = 'blah blah';
        $scope.message = 'Good day';
        var returnedTemplate = '<div><h3 class="md-title">{{name}}</h3><p class="md-title">{{message}}</p></div>';
        var element = $compile(returnedTemplate)($scope);

        $timeout(function() {
            var confirmDialogMessage = element.html(); // needed time
            console.log(confirmDialogMessage); // here I got the html with values in, but still in a string

       }, 300);
        
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl"></div>