【问题标题】:how to get data by using ID in angular js?如何在angular js中使用ID获取数据?
【发布时间】:2015-12-03 16:02:09
【问题描述】:

我正在尝试在我的演示中使用 angular-resource.js 文件。我正在检索 使用 $resource 来自 json 文件的数据并使用 ng-repeat 显示我的数据。但是我添加了一个按钮(信息文本按钮)的每个项目。我需要使用它来获取信息$resource 属性。我在点击功能上发送 ID。但是当我使用 $resource 属性时,它会给我错误

 $scope.getIn=function(id){
     // alert(id)
      $scope.oneUser = Entry.get({user: id});
      console.log($scope.oneUser)
    } 

这是我的代码 http://plnkr.co/edit/lB11oQkQjbILK36u8V25?p=preview

【问题讨论】:

  • 好吧,$resource 旨在使用 REST API,但您正试图从 JSON 文件中获取一些东西。

标签: angularjs angularjs-directive angularjs-scope angular-ui-router


【解决方案1】:

如果我正确理解您要实现的目标,应该可以解决它:

  angular.module('app',['ngResource']).controller('a',function($scope, GetData){
    // read data from factory and store it in $scope.posts 
     GetData.then(
        function successCallback(data) {
             $scope.posts = data.data;
        },
        function errorCallback(response) {
           console.log(response); // handle any errors
        });

    // buttonclick to return the values from the selected id
      $scope.getIn = function(id){
        angular.forEach($scope.posts, function(value) {
          if(value.id === id)
          {
            $scope.selectedValue = value;
          }
        })
      };

    console.log($scope.posts)
  })
  .factory('GetData', function($http){ // use http to read the json
    return $http.get('data.json');
  });

还有html:

  <body ng-app='app' ng-controller='a'>
    <div ng-repeat='p in posts'>
      <span>{{p.name}}</span>
      <button ng-click=getIn(p.id)>info</button>
    </div>
    {{selectedValue}}
  </body>

【讨论】:

    猜你喜欢
    • 2018-05-26
    • 2019-05-07
    • 1970-01-01
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多