我正在尝试编译已定义data-ng-include
和data-ng-src
的模板。我试图通过调用getPartial()
来设置src,它返回模板的路径。但是getPartial()
没有被调用。
HTML:
<button ng-click="displayElements();">Display Elements</button>
<div id="container"></div>
JS:
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-src="getPartial()"></div>';
var linkFn = $compile(template)($scope);
//console.log(angular.element(document.getElementById("container")));
angular.element(document.getElementById("container")).append(linkFn);
}
$scope.getPartial = function() {
console.log("from partial");
return 'hello.html';
}
答案 0 :(得分:3)
ng-include
使用自己的值或src
属性值来获取路径(see documentation)。您正在尝试使用ng-src
,directive in its own right。所以你需要这样做:
<div data-ng-include="getPartial()"></div>
或者这个:
<div data-ng-include data-src="getPartial()"></div>
在旁注中,观看功能调用结果会影响性能。通过将已解析的源路径放入范围变量,您可以获得更好的服务。
答案 1 :(得分:1)
以下是解决方案: -
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile) {
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var linkFn = $compile(template)($scope);
angular.element(document.getElementById("container")).append(linkFn);
};
$scope.getPartial = function() {
alert("from partial");
$scope.htmlToLoad = 'hello.html';
};
}]);
答案 2 :(得分:0)
'<div data-ng-include data-ng-src="getPartial()"></div>';
用这个
替换你的代码'<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', '$compile', function($scope, $compile) {
$scope.displayElements = function() {
var template = '<div data-ng-include data-ng-init="getPartial()" src="htmlToLoad"></div>';
var linkFn = $compile(template)($scope);
//console.log(angular.element(document.getElementById("container")));
angular.element(document.getElementById("container")).append(linkFn);
}
$scope.getPartial = function() {
alert("sdfsdfsdf");
console.log("from partial");
return 'hello.html';
}
}]);