0

我是angular.I的新手,我正在做一个简单的演示,其中我将根据当前选定的值添加新的选择。我很喜欢选项和模型的动态价值。我无法获得选定的值,请帮助。获取角度js中的选定值

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"}]}); 
} 

这里的型号名称是宠我虽然$ scope.pet这是给不确定的。

回答

1

如果您想使用$ scope.pet为你的模型,那么你需要使用它的NG-模式指令是这样的:

(NG-模型就是选择价值被分配)。

<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.pet赋值,让您的下拉菜单预先填充... $ scope.pet =“Cat”;

你的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-模型值表达的方式,角度值分配给的“模型”属性$ scope.selects对象。如果您检查$ scope.selects(角度Batarang或类似的Chrome插件)数组,您将在其中一个对象的model属性中看到您将具有您选择的正确值,但您只是将它分配给错误的位置。

如果您需要多个选择和模型,您可以使用现有对象模型属性或类似的模型,在您的ng模型中使用a.model,然后在ng-change中,您将传递“index”选择“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); 

} 
+0

好吧,但它。如果我提供一个用于添加多个选择按钮的按钮,该怎么办?在这种情况下,我需要定义多个模型。那该怎么办呢。 – Madan

+0

@马丹我用你需要的信息编辑了答案。 –

+0

@马丹我回答你的问题了吗? –