【问题标题】:How to bind WebAPI Getall result to Select option using AngularJS如何使用 AngularJS 将 Web API Get All 结果绑定到 Select 选项
【发布时间】:2015-04-20 21:48:52
【问题描述】:

我正在尝试将我的 WebAPI Get 结果绑定到 angular ng-option 并且在这样做时遇到了一点困难,我将非常感谢你们对此做出的任何贡献。

这就是我目前所做的

这是我的 API

        public IHttpActionResult Get()
    {
        try
        {
            var testcategories = _Service.GetTestCategories();
            if (testcategories != null)
            {
                return Ok(testcategories);
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);

        }
    }

现在这是用于获取测试类别的 Angular 控制器

vm.getTestCategories = function () {
        $scope._testCategories = TestCategory.query();
        console.log(_testCategories);
    };

这是我试图绑定的 HTML

<div class="col-sm-9">

    <div class="input-group">
    <select name="TestCategory" class="form-control mb-10" id="TestCategory" ng-model="_test.TestCategory" ng-options="_testCategory.Id as _testCategory.Name for" on-blur-validation required><option ng-repeat="c in _categories._categories" value="{{c.Id}}">{{c.Name}}></option></select>

    <span class="input-group-btn">
    <button class="btn btn-info btn-rounded btn-ef btn-ef-5 btn-ef-5a mb-10" onclick="toggle()"><span>Add</span> <i class="fa fa-plus"></i> </button>
     </span>
     </div>

     <p class="help-block">
     <span ng-show="testForm.TestCategory.$invalid && !testForm.TestCategory.$pristine">Test Category is Required.</span>
      </p>

然后我尝试将其记录到控制台,如您所见,它工作得很好。那么如何将它绑定到字体端的选择列表。

感谢您对此的意见。

【问题讨论】:

    标签: javascript angularjs asp.net-web-api


    【解决方案1】:

    您可以对select 元素使用标准角度语法

    <select name="TestCategory" class="form-control mb-10" id="TestCategory" 
            ng-model="_test.TestCategory"  
            ng-options="_testCategory.Id as _testCategory.Name for _testCategory in _testCategories" on-blur-validation required>
    </select>
    

    $scope._testCategories 您的类别数组在哪里。 然后选定的项目 id 将存储到 ng-model 表达式中(在提供的示例中为$scope._test.TestCategory)。如果您想默认选择某个项目,请使用该元素的 id 设置 $scope._test.TestCategory

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2015-01-19
      • 2018-02-22
      • 2020-03-29
      • 2022-01-19
      相关资源
      最近更新 更多