Angular JS,是否可以动态设置ng-include或ng-controller?

5

我是Angular JS的新手,通过研究发现似乎不可能做到这一点,但我想再次确认/看看是否有某些替代方案可以达到类似的结果。

我想要做的是从JSON文件中填充页面,并使用在该JSON文件上的url加载自定义li。例如:

JSON / 控制器内部:

function ExCtrl($scope) {

    $scope.examples = [
            {name:"example", 
            num: 1, 
            url:"website.html"}
        ];
    }

JS(内嵌JS)

<ul ng-controller="ExCtrl">
   <li ng-repeat="example in examples">
      <div ng-include src="folder/{{example.url}}> </div>
   </li>
</ul> 

解决方案:
<ul ng-controller="ExCtrl">
   <li ng-repeat="example in examples">
      <div ng-include src="example.url"> </div>
   </li>
</ul> 

现在的情况是:
function ExCtrl($scope) {

    $scope.examples = [
            {name:"example", 
            num: 1, 
            url:"folder/website.html"}
        ];
    }
1个回答

5

从文档中得知:

ngInclude|src{string} – Angular表达式求值为URL。如果源是字符串常量,请确保用引号括起来,例如:src="'myPartialTemplate.html'"

在您的情况下,设置自定义ngResource是有意义的。在控制器中,注入资源并查询JSON,然后将JSON分配给作用域变量。

angular.module("foo", "ngResource")

  .factory("ResourceType", function($resource){
    return $resource("/resourcetype/:id", {id: "@id"}, { "update": {method:"PUT"}});
  })
  .controller("ExCtrl" function($scope, ResourceType){
    $scope.examples = ResourceType.query();  
  });

当您循环遍历资源时,您需要设置ng-include的URL。

另外,不要使用{{}}来命名变量。

编辑:

我本来想给您一个Plunker,但它似乎出了点问题。这里是一段内联源代码,可以实现您想要的效果。为了清晰起见,我删除了资源部分。我想当您决定远程检索JSON时,您会想把它放回去。

<!DOCTYPE html>
<html ng-app="angularjs-starter">

  <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <ul ng-controller="MainCtrl">
      <li ng-repeat="example in examples">
        If {{example.url}} were valid, it would load in the div. 
        <div ng-include="example.url"> </div>
      </li>
    </ul> 
  </body>
</html>

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.examples = [
     {name:"example", 
      num: 1, 
      url:"example.html"}
  ];
});

编辑:Plunk

http://beta.plnkr.co/edit/JNhqoJoykWKf4iqV0ieJ?p=preview

注:该链接为Plunk网站的编辑页面。

非常抱歉,我对此还很陌生,我很难理解该函数的每个部分是在做什么或整体目标是什么。这是一个从控制器设置URL的函数吗? - Alex
我更新了我的问题,更好地反映了我的当前系统,如果这有帮助的话。现在我能够正确解析我的URL了,它会显示ng-include src="example.html"而不是example.url,但它还没有加载它? - Alex
我刚刚修改了您的代码,现在它在 Plunker 上可以运行了。正在检查我的代码。 - Alex
我仍在尝试从JSON数据中加载URL,但似乎将其放在子文件夹中会导致出现问题。nginclude="folder/example.url"无法正常工作。 - Alex
好的,我可以在我的数据URL前面加上前缀(例如= [{name... url:“folder/example.html”..)这样就能工作了,但我真的不希望那个前缀必须在那里,但是这样也行。感谢您的耐心等待。 - Alex
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接