0

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

$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 函数将数据绑定到字符串,但无济于事。

在此先感谢您的帮助

4

2 回答 2

1

绑定后需要手动编译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 中调用 this 并将 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>

于 2017-04-09T06:01:22.730 回答
0

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

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>

于 2017-04-09T14:13:15.033 回答