简体   繁体   English

如何在angularjs中的对象中选择内容中设置值

[英]How to set a value in a select from an object in angularjs

I'm new to Angular so please be gentle :) 我是Angular的新手,所以请保持柔和:)

I am recieving a "Brand" Object from the server and I want to set the select field with the good corresponding value. 我正在从服务器接收一个“品牌”对象,我想为选择字段设置良好的对应值。

Brands look like this : 品牌看起来像这样:

Brands = [{name: "BRAND1", id=242},
          {name: "BRAND2", id=562}]

And I got from the server: 我从服务器得到了:

brandFromTheServer = {name: "BRAND2", id=562};

This is my select : 这是我的选择:

<select id="brand" ng-model="product.brand" class="form-control" ng-options="brand as brand.name for brand in brands"></select>

And I want the select to be set with brandFromTheServer. 我希望使用brandFromTheServer设置选择。

I tried in the controller: 我在控制器中尝试过:

$scope.product.brand = brandFromTheServer;

How can I set the value of the select with the brand that I'm recieving ? 我该如何根据自己选择的品牌设置精选商品的价值?

Sorry, my English is terrible ! 抱歉,我的英语太糟糕了! Please help :=) 请帮助:=)

<select id="brand" ng-model="product.brand" class="form-control" ng-     options="brand as brand.name for brand in brands">
   <option value="o">Val 1</option>
   <option value="1">Val 2</option>
   <option value="2">Val 3</option>
</select>

$scope.product.brand = 0 or 1 or 2; $ scope.product.brand = 0或1或2;

I use something like this: 我用这样的东西:

   <select ng-options="option.name for option in advertiserList" ng-model="selectedOption.advertiserChoice" class="form-control"></select>

And in my controller I have: 在我的控制器中,我有:

$scope.advertiserList = response.advertisers;
            var data = $scope.advertiserList.getIndexBy("id",  $scope.currentAdvertiser.id)
            $scope.selectedOption.advertiserChoice = $scope.advertiserList[data];

The method getIndexBy() is like this: 方法getIndexBy()如下所示:

Array.prototype.getIndexBy = function (name, value) {
          for (var i = 0; i < this.length; i++) {
              if (this[i][name] === value) {
                  return i;
              }
          }
      }

And my advertiserList json looks like this: 我的advertiserList json如下所示:

"advertisers": [
    {
      "id": 1,
      "name": "Somebody Franck",

    },
    {
      "id": 2,
      "name": "Me Me me",

    }
]

Your approach is correct when using ng-options, however the product.brand is not bound to the Brand object. 使用ng-options时,您的方法是正确的,但是product.brand未绑定到Brand对象。 Something like this works: 像这样的作品:

Controller: 控制器:

$scope.brands = [
    {
      name: '1'
    },
    {
      name: '2'
    },{
      name: '3'
    }

  ];

  $scope.product = {
    brand: $scope.brands[1] // now it has a 'reference'
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM