【问题标题】:How to send the data from the textbox to the controller if the some value from the dropdown list is selected in AngularJS?如果在 AngularJS 中选择了下拉列表中的某个值,如何将数据从文本框发送到控制器?
【发布时间】:2018-05-15 15:02:01
【问题描述】:

我有一个下拉列表。在那有一些价值。如果该值不存在,则用户可以在该下拉列表中选择 Other 选项。如果选择 Other 我必须显示文本框。我这样做了。

我的要求如下:

如果选择了下拉列表中的选项,我想将此选定值访问到特定变量中的控制器中,例如 $scope.myvalue。如果选择了“其他”选项,那么我想在同一变量(即 $scope.myvalue)中访问从文本框到控制器的值。

在 index.html 我有以下代码:-

{

<select data-ng-model="selectedName" ng-options="x for x in colors" >
</select>
<input type="text" ng-show="selectedName=='Other'" >

}

在我的控制器中,我有以下代码

app.controller('myCtrl', ['$scope', function($scope) {
$scope.colors = ["Black","Red","Orange","Other"];

}]);

在选择列表中,我只有黑色、红色和橙色三种颜色。如果用户想要选择其他颜色,那么他将从选择列表中选择其他选项。 When is selects the Other option, a textbox should appear where he can enter color.

现在,如果用户从选择列表中选择了颜色,例如 Red,那么这应该可以在控制器中的某个 x 变量中访问。如果用户从选择列表中选择了 Other 选项,则会出现一个文本框,他将输入一些颜色,例如用户输入了 Blue,那么这也应该可以在控制器在同一个变量 x 中。 即,无论用户从选择列表中选择了什么值或用户输入了文本框,我都必须将该值放在控制器中的同一变量中。

【问题讨论】:

  • 目前已经尝试过什么
  • 只需在&lt;select&gt; 上使用ng-change 并检查&lt;select&gt; 的模型值

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

据我了解,您的问题是这样的:

HTML:

<div ng-controller="myController">

<!-- Some code here -->

<select ng-model="myValue">
   <option value="-1">Other</option>
   <option value="100">something</option>
</select>

<!-- Some code here -->

<input type='text' ng-model="myText"/>

</div>

然后在你的 controller.js 中:

myModule.controller('MyController', function($scope){

   $scope.$watch('myValue', function(newValue, oldValue)
   {
        if (newValue == -1)
        {
           $scope.myText = "Other Text";
        }
        else
           $scope.myText = "Something else"; 
   });
});

这里的“技巧”是使用 $scope.$watch 来检查控制器范围内的变量是否发生了变化。

这是文档https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-17
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多