ng-include与ng-src无法正常工作

时间:2014-12-06 10:47:40

标签: angularjs

我正在尝试编译已定义data-ng-includedata-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';
}

Plnkr:http://plnkr.co/edit/ig9TAXVpK4k1bQwi9PQo?p=preview

3 个答案:

答案 0 :(得分:3)

ng-include使用自己的值或src属性值来获取路径(see documentation)。您正在尝试使用ng-srcdirective 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';
};
}]);

http://plnkr.co/edit/y3PgeBMVHytftI7NDSq4?p=preview

答案 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';
}
}]);