【问题标题】:AngularJS - Chosen ng-model is not working properlyAngularJS - 选择的 ng-model 工作不正常
【发布时间】:2018-04-20 20:02:57
【问题描述】:

当我从 AngularJS 选择的 localytics 下拉列表中选择一个选项时,我试图获得价值。 这是下拉菜单的代码:

<select chosen style="width: 250px"
        ng-model="StudentId"
        ng-options="allStudent.StudentId as allStudent.Name for allStudent in allStudent">
        <option value="">Select</option>
</select>
<h2>Chosen with static options: {{ StudentId }}</h2>
<input type="button" value="Search" ng-click="GetStdCourseList(StudentId)">

在我的控制器中,我有以下功能:

    $scope.GetStdCourseList = function (StudentId) {
        alert(StudentId);
    };

当我使用警报时,它会显示“未定义”而不是显示值 我该如何解决这个问题?

实际上这没问题,当我不使用选择的搜索时我会得到价值,但是当我使用“选择”时它就不起作用了....这是屏幕截图:

非常感谢。

【问题讨论】:

  • 由于您的模型是 StudentId,您可以忽略函数中的参数并简单地使用 $scope.StudentId
  • chosen 属性是关于什么的?

标签: javascript jquery angularjs


【解决方案1】:

我认为您在单击按钮之前没有选择任何选项。当我选择该选项时,这对我来说很好。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.allStudent = [{StudentId: 0, Name: 'name1'}, {StudentId: 1, Name: 'name2'}];
     $scope.GetStdCourseList = function (StudentId) {
        alert(StudentId);
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <select chosen style="width: 250px"
          ng-model="StudentId"
          ng-options="allStudent.StudentId as allStudent.Name for allStudent in allStudent">
          <option value="">Select</option>
  </select>

  <h2>Chosen with static options: {{ StudentId }}</h2>
  <input type="button" value="Search" ng-click="GetStdCourseList(StudentId)">
</div>

【讨论】:

  • 谢谢 Nitheesh。但我认为您的代码中使用的“选择”不起作用。请检查我的帖子的屏幕截图..
  • @SubhoGhose 这个选择的属性有什么用?
【解决方案2】:

好吧,既然 ng-model 的对象是 $scope.something 本身,请尝试

替换

alert(StudentId)

成为

alert($scope.StudentId)

我认为在这种情况下您不需要参数。忽略它,因为 $scope 为你覆盖了它

这样就可以了

经过编辑以提高可读性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2013-05-14
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多