2017-04-09 49 views
0

我有我的控制器此功能,它加載在模板角綁定範圍數據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> 

我曾嘗試使用$編譯功能,將數據綁定到字符串,但無濟於事。

在此先感謝您的幫助

回答

0

您需要手動編譯後綁定的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>

+0

謝謝你這一點,你明確指出我在寫方向。在玩了很多遊戲之後,我想到了這一點。 – Sprep

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>