ng-include和src不支持动态更改

时间:2015-09-09 11:32:29

标签: angularjs

我有类似下面的内容。我是一个有约束力的国家。

在下拉列表更改中,我将显示不同的视图。

 $scope.countries = [{id : 1, name : 'USA'}, {id : 2, name : 'India'}, {id: 3, name :'MIGHTY USSR'}];


 <select class="form-control" ng-model="selectedCountry" ng-options="country as country.name for country in countries">
    <option value="">Select Country</option>
 </select>

-

<div class="animate-switch-container" ng-switch on="selectedCountry.name">
<div class="animate-switch" ng-switch-when="USA">
      This Text is showing

      <div ng-include="'partials/USA.html'"></div>       -- Not Working
</div>

<div class="animate-switch" ng-switch-when="India">
     <div ng-include="'partials/'+ selectedCountry.name + '.html'"></div>       -- I tried this as well
</div>

<div class="animate-switch" ng-switch-default>
     Other Country
</div>

我还试过<div ng-include="'partials/USA.html'"></div>&amp; <div ng-include src="'partials/USA.html'"></div>

我的app文件夹如下所示

app
    views
        partials
           USA.html
           India.html
    dashboard.html
Index

有任何解决方案吗?

3 个答案:

答案 0 :(得分:3)

尝试如下

更改ng-options,如下所示

.. ng-options="country.id as country.name for country in countries"..>

然后当您选择下拉选项时,selectedCountry的值会获取该选项的ID值,如果您选择USA,则selectedCountry值将为1 },基于该ID,您可以包含您想要的.html文件,

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

并将.html文件保存为1.html的{​​{1}}和USA的{​​{1}}

这是一个DEMO

并注意,如果您更喜欢命名2.html文件,例如India&amp; .html然后只需将India.html更改为

即可
USA.html

DEMO

答案 1 :(得分:1)

您不应将html页面直接包含在ng-include

绑定控制器中的html页面

像这样使用:

<强>标记

<div ng-include="usaPage"></div>

<强> JS

$scope.usaPage = "partials/USA.html";

对于所选国家/地区:

<强>标记

<div ng-include="SelectedCountryPage"></div>

<强> JS

// in your selection event like ng-click
$scope.SelectedCountryPage = "partials/" + $scope.selectedCountry.name + ".html";

更新:

这是工作Plunker

答案 2 :(得分:0)

问题在于您的{{}}(以及"):

'partials/'+{{selectedCountry.name}}+"'.html'

ng-include不希望如此。而是做:

ng-include="'partials/'+ selectedCountry.name + '.html'"