通过单击动态内容中的按钮获取对象的属性

时间:2017-05-26 11:38:19

标签: angularjs arrays object dynamic key-value

我对angularjs完全不熟悉。 我使用包含对象的数组创建了一些动态内容。 现在,我的动态内容有一个按钮,它将调用一个方法从'myData'数组中获取对象的相应ID。

我很困惑如何编写此方法以从myData数组中获取相应对象的id。

你能帮帮我吗?

这是代码

angular.module('myApp', []).controller('myCtrl', function($scope){
  $scope.myData = [{
    company: "ABC",
    url: "www.abc.com",
    type: "company",
    id: "1"
  }, {
    company: "CDE",
    url: "www.cde.com",
    type: "company",
    id: "2"
  }, {
    company: "DEF",
    url: "www.def.com",
    type: "company",
    id: "3"
  }];


  $scope.getID = function() {
    console.log(this);

  };

});
.event {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: skyblue;
  margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="obj in myData" class="event">
    Company: <span>{{obj.company}}</span>
  <br /><br />
  Type: <span>{{obj.type}}</span>
  <br /><br />
  URL: <span>{{obj.url}}</span>
  <br /><br />
  <button ng-click="getID()">Get ID</button>
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

<button ng-click="getID(obj.id)">Get ID</button> // pass id from template to controller



  $scope.getID = function(id) {
     $scope.forEach(function(obj){ // loop through your data
         if(obj.id === id) { // if passed id equals to object id
            console.log(obj) // get desired object
         }
     })

  };

或者你可以像

那样做
<button ng-click="getID(obj.id, myData)">Get ID</button>

  $scope.getID = function(id, myData) {
     myData.forEach(function(obj){
         if(obj.id === id) {
            console.log(obj) // desired object
         }
     })

  };

答案 1 :(得分:1)

只需将obj.id作为函数参数传递:

&#13;
&#13;
angular.module('myApp', []).controller('myCtrl', function($scope){
  $scope.myData = [{
    company: "ABC",
    url: "www.abc.com",
    type: "company",
    id: "1"
  }, {
    company: "CDE",
    url: "www.cde.com",
    type: "company",
    id: "2"
  }, {
    company: "DEF",
    url: "www.def.com",
    type: "company",
    id: "3"
  }];


  $scope.getID = function(id) {
    console.log(id);

  };

});
&#13;
.event {
  height: 150px;
  width: 250px;
  border: 1px solid black;
  border-radius: 3px;
  background-color: skyblue;
  margin-top: 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-repeat="obj in myData" class="event">
    Company: <span>{{obj.company}}</span>
  <br /><br />
  Type: <span>{{obj.type}}</span>
  <br /><br />
  URL: <span>{{obj.url}}</span>
  <br /><br />
  <button ng-click="getID(obj.id)">Get ID</button>
  </div>
</div>
&#13;
&#13;
&#13;