【问题标题】:Bind particular value from array object in angularJS在angularJS中绑定数组对象的特定值
【发布时间】:2017-02-23 10:31:22
【问题描述】:
testing:{"name":"Mohan,Rahul,Kanal,Rajesh,Gokul,Ramesh"}  

假设我想使用角度 ng-repeat 将前三个名称绑定到标签中。这可能吗。帮助我。提前致谢

【问题讨论】:

  • ng-repeat中使用limit
  • 使用如下格式。 {{姓名 | limitTo:3}} 但它只需要三个字符串长度。

标签: angularjs arrays object


【解决方案1】:

请查看以下代码,这可能有助于解决您的问题。

<!DOCTYPE html>
    <html>
    <body>
        <div ng-app="myApp" ng-controller="sizeCtrl">
            <ul>            
            <li ng-repeat="x in arr | limitTo:3">{{x}}</li>
            </ul>
        </div>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> 
        <script>
        var app = angular.module('myApp', []);
        app.controller('sizeCtrl', function($scope) {
            $scope.arr = [];
            $scope.cars = {name: "Audi,BMW,Dodge,Fiat,Ford,Volvo"};
            $scope.arr = $scope.cars.name.split(",");
        });
        </script>
    </body>
</html>

【讨论】:

    【解决方案2】:

    像这样试试。

    var app = angular.module("app",[]);
    
    app.controller('MainCtrl', function($scope) {
    
      $scope.testing={"name":"Mohan,Rahul,Kanal,Rajesh,Gokul,Ramesh"}  
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="app" ng-controller="MainCtrl">
      <div ng-repeat="(key,value) in testing.name.split(',') | limitTo:3 ">
      <p >{{value}}</p>
      </div>
    </div>

    【讨论】:

      【解决方案3】:

      你可以使用ng-repeat:

        <label>
          <span ng-repeat="name in testing.name.split(',') | limitTo:3">
            {{name}}<span ng-show="$index<2">,</span>
          </span>
        </label>
      

      另一种解决方案:这以数组格式显示前三个名称:

      {{testing.name.split(',') | limitTo:3}}
      

      另一种解决方案:您可以拆分字符串,然后将前三个连接到另一个范围变量并绑定到它。

      var arr = $scope.testing.name.split(',');
      $scope.labelStr = "";
      for(var i=0; i<3; i++) {
          $scope.labelStr += arr[i] + ',';
      }
      $scope.labelStr = $scope.labelStr.substr(0, $scope.labelStr.length-1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-31
        • 2021-12-12
        • 2020-10-29
        • 1970-01-01
        • 2013-12-19
        • 1970-01-01
        • 2015-08-14
        • 2017-08-19
        相关资源
        最近更新 更多