在angular js中获取选中的值

Get selected value in angular js

本文关键字:获取 js angular      更新时间:2023-09-26

我是angular的新手。我正在为选择做一个简单的演示,我将根据当前选择的值添加新的选择。我使用动态值的选项和模型以及。我无法获得所选值,请帮助。

HTML代码放在这里:

<md-input-container ng-repeat="a in selects" class="md-block"  style="margin-top:20px;">
      <label>{{a.label}}</label>
      <md-select required  ng-model="a.model" ng-change="callme()" flex="40">
        <md-option ng-model="a.model" ng-repeat="optionValue in a.options" ng-value="optionValue.option">
            {{optionValue.option}}
        </md-option>
      </md-select>
      <div class="errors" ng-messages="petApp.favoriteColor.$error">
            <div ng-message="required"> You need to select a option</div>
      </div>
  </md-input-container>

JS代码在这里

$scope.selects =  [{label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]}];
$scope.callme = function(){
  console.log($scope.pet);
  $scope.selects.push({label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]});
}

这里模型名称是pet,而我做$scope。

如果你想使用$scope。把它作为你的模型,然后你需要在ng-model指令中使用它,像这样:

(ng-model是指定选择值的地方)。

<md-input-container ng-repeat="a in selects" class="md-block"  style="margin-top:20px;">
      <label>{{a.label}}</label>
      <md-select required  ng-model="pet" ng-change="callme()" flex="40">
        <md-option ng-repeat="optionValue in a.options" ng-value="optionValue.option">
            {{optionValue.option}}
        </md-option>
      </md-select>
      <div class="errors" ng-messages="petApp.favoriteColor.$error">
            <div ng-message="required"> You need to select a option</div>
      </div>
  </md-input-container>

你也应该确保你的$scope。在呈现页面之前声明Pet变量。你可以给$scope赋值。宠物有你的下拉菜单预填充…美元的范围。

你的js代码应该看起来像这样:

$scope.pet = ""; // or you may assign pet a value if you like
$scope.selects =  [{label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]}];
$scope.callme = function(){
  console.log($scope.pet);
  $scope.selects.push({label:"Your Pet",model:"pet",options:[{option:"Cat"},{option:"Dog"},{option:"Guinea pig"}]});
}

你现在用a.model作为ng-model值的表达方式是,Angular把这个值赋给$scope的"model"属性。选择对象。如果你检查$作用域。选择(角Batarang或类似的chrome插件。)数组,你会看到在一个对象的模型属性,你将有你选择的正确值,但你只是分配给错误的地方。

在你需要多个选择和模型的情况下,你会使用你现有的对象模型属性或类似的东西,a.model在你的ng-model,然后在ng-change你会传递"a"的"索引"在选择。

<md-select required  ng-model="a.model" ng-change="callme($index)" flex="40">

所以当你的"callme"函数被调用时,你可以通过下面的操作看到选择的值。

$scope.callme = function(index){
  console.log($scope.selects[index].model);
}