AngularJS ng-include does not include view unless passed in $scope

♀尐吖头ヾ 提交于 2019-11-26 18:57:31

问题


Is it wrong to assume that ngInclude can take a raw path? I keep trying to set my ngInclude as follows:

<div ng-include src="views/header.html"></div>

This does not work but if I do something like this it does work.

// HeaderController
app.controller('HeaderCtrl', function($scope){
   $scope.templates = {[
     template: { url: 'views/header.html' }
   ]};

   $scope.template = $scope.templates[0].template;
});

In my index.html

<div ng-controller="HeaderCtrl">
  <div ng-include src="template.url"></div>
</div>

Does ngInclude only except values off of the scope? If so why is it this way and not a straight include of the html partial.


回答1:


ng-include accepts an expression. If you want to specify the explicit URL directly in there, you have to give a string.

<div ng-include src="'page.html'"></div>



回答2:


ng-include, as other directives (ng-class, ng-src ...) evaluates an Angular expression from the scope. Without quotes (''), it will search for a variable of the scope.


Note that you don't have to specify the src attribute.

<div ng-include src="'views/header.html'"></div>

Can be rewritted to: (that is simpler)

<div ng-include="'views/header.html'"></div>

You can also use ng-include as an element:

<ng-include src="'views/header.html'"></ng-include>


来源:https://stackoverflow.com/questions/12521905/angularjs-ng-include-does-not-include-view-unless-passed-in-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!