【问题标题】:How to put Value from JSON API to Angular Template Directive如何将 JSON API 中的值放入 Angular 模板指令
【发布时间】:2016-10-10 07:52:35
【问题描述】:

我是新手,我想问一下。

我想从 JSON API(title、course_id 等)中获取一些值,然后将值放入带有指令的模板中。所以在 Index,我可以使用来自 API 的数据重复我的模板。

如何从该 JSON 中获取价值?

这是我的代码:

我的 API

{
"count": 1,
"next": null,
"previous": null,
"results": [
    {
        "url": "http://192.168.1.37:8000/api/courses/a/",
        "title": "I Love You",     <-- I want to put this Value to my Template
        "course_id": "1",
        "starting_date": "2016-10-03"
    }
           ]
}

控制器 demo.js

demo.controller("demo", function($scope, $http) {
$http.get('http://192.168.1.37:8000/api/courses/'). <-- Data From my API
    then(function(response) {
        $scope.courses = response.data;
    });


    });

demo.directive("demoItemDirective", function() {
   return {
        scope : { demoInfo : "=info"},
        templateUrl : "/app/demo.tmpl"   <-- My Template
    };
   });

我的模板 demo.tmpl

<p>{{demoInfo.count}}</p>                <-- Works, count Displayed
<p>{{demoInfo.results.title}</p>         <-- Not works, title not displayed

我的 Index.html

   <div ng-repeat="group in courses | groupCount:2">
   <div ng-repeat="x in group">
        <demo-item-directive info="x"></demo-item-directive>
   </div>
   </div>

【问题讨论】:

    标签: javascript jquery angularjs json


    【解决方案1】:

    应该是

    <p>{{demoInfo.results[0].title}</p>  
    

    您的结果包含一个对象数组。

    你需要用索引访问。

    【讨论】:

      【解决方案2】:

      根据您的帖子,result 是一个数组:

      "results": [
          {
              "url": "http://192.168.1.37:8000/api/courses/a/",
              "title": "I Love You",     <-- I want to put this Value to my Template
              "course_id": "1",
              "starting_date": "2016-10-03"
          }
      ]
      

      因此,您不能引用title 本身,您必须引用第一个元素:

      {{demoInfo.results[0].title}}

      【讨论】:

      • 谢谢伙计,这就是工作!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多