如何在选择框或下拉列表中默认选择第一个选项

时间:2022-03-08 19:45:04

I am trying to display select box using directive. But my default option is not display.

我试图使用指令显示选择框。但我的默认选项不显示。

I do like this

我喜欢这个

<div>
    <select ng-init="userselected = vm.data[0]"
            ng-model="userselected"
            ng-options="option.name for option in vm.data">
    </select>
</div>

Here is my code http://plnkr.co/edit/Q1e8u0okOa4looLcb2YO?p=preview

这是我的代码http://plnkr.co/edit/Q1e8u0okOa4looLcb2YO?p=preview

.controller('f',function($http){
        var l=this;
        $http.get('data.json').success(function(data){
          l.data=data;
        })
      })

Can we load data before calling controller and loading the html file using resolve?

我们可以在调用控制器之前加载数据并使用resolve加载html文件吗?

5 个解决方案

#1


0  

Can we load data before calling controller and loading the html file using resolve?

我们可以在调用控制器之前加载数据并使用resolve加载html文件吗?

Yes. The way to do that would be to resolve the dataset you want to expose onto your view before initialising the controller attached to said portion of the view.

是。这样做的方法是在初始化附加到视图的所述部分的控制器之前解析要在视图上公开的数据集。

I can think of three ways off of the top of my head;

我可以想到三个方面;

  • ui-router#resolve.
  • UI路由器#决心。
  • ngRoute#resolve.
  • ngRoute#决心。
  • defer compilation of the DOM attached to your controller.
  • 推迟编译附加到控制器的DOM。

ui-router#resolve

// state definition
.state('myState', function () {
  resolve: {
    dataset: function (Service) {
      return Service.getData();
    }
  },
  controller: 'Controller'
})
// controller definition
.controller('Controller', function (dataset) {
  this.dataset = dataset;
})

The resolved data will be available under the given name in the controller attached to the state definition (through the definition itself, or with a ng-controller at the root of your state template).

已解析的数据将在附加到状态定义的控制器中以给定名称提供(通过定义本身,或者在状态模板的根目录下使用ng-controller)。

ngRoute#resolve

// route definition
.when('/path', {
  resolve: {
    dataset: function (Service) {
      return Service.getData();
    }
  },
  controller: 'Controller'
})
// controller definition
.controller('Controller', function (dataset) {
  this.dataset = dataset;
})

Pretty much the exact same way as the ui-router example.

几乎与ui-router示例完全相同。

ngIf

Defer the rendering of your template, by waiting for the promise to resolve.

通过等待承诺解决来推迟模板的呈现。

.controller('outer', function ($timeout) {
  this.resolved = false;
  this.dataset  = [];

  $timeout(function () {
    this.resolved = true;
    this.dataset = [ {}, {} ];
  }.bind(this), 1500);
})
.controller('inner', function () {
  console.log('I just ran!');
})

<div ng-controller="outer as o">
  <div ng-controller="inner as i" ng-if="o.resolved">
    {{o.dataset}}
  </div>
</div>

jsfiddle of the last solution

jsfiddle的最后一个解决方案

#2


0  

Check it out. So with angular you should be binding your model with the HTML elements using $scope.

一探究竟。因此,对于angular,您应该使用$ scope将模型与HTML元素绑定。

http://plnkr.co/edit/dVI0MDC5k4AVSJAOMyy3?p=preview

http://plnkr.co/edit/dVI0MDC5k4AVSJAOMyy3?p=preview

The way I resolved this was to store your data to a scoped variable, and setting the init value to the first index in the array

我解决这个问题的方法是将数据存储到作用域变量,并将init值设置为数组中的第一个索引

controller('f',function($http, $scope){
    $scope.vm = null;
    $scope.userselected = null;
    $http.get('data.json').success(function(data){
      $scope.vm=data;
      $scope.userselected = $scope.vm[0];
    })
  })

And the changes to your HTML:

以及对HTML的更改:

    <select ng-model="userselected"
            ng-options="option.name for option in vm">
    </select>

#3


0  

Your problem is that vm.data is being populated asynchronously. When the view first loads and the ng-init is run, vm.data[0] is undefined, which is why it doesn't work. A quick fix is to add ng-if="vm.data" to the wrapper div so that the content within the ng-if is only added to the dom after vm.data is defined.

您的问题是vm.data是异步填充的。当视图首次加载并运行ng-init时,vm.data [0]未定义,这就是它不起作用的原因。快速解决方法是将ng-if =“vm.data”添加到包装器div中,以便ng-if中的内容仅在定义vm.data后添加到dom中。

Also, Julian's answer is definitely a better solution. ng-init is usually a bad way to initialize values - it is much preferred that you initialize them in a controller.

此外,朱利安的答案绝对是一个更好的解决方案。 ng-init通常是一种初始化值的坏方法 - 最好在控制器中初始化它们。

#4


0  

Here is a demo on how to set the default value in select option.

这是一个关于如何在select选项中设置默认值的演示。

Use: set the value using ng-model

使用:使用ng-model设置值

HTML:

HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-with-default-values-production</title>  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
  <script src="app.js"></script>

</head>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions track by option.id"
      ng-model="data.selectedOption"></select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>

JS:

JS:

(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
     };
 }]);
})(window.angular);

Reference: Using select with ngOptions and setting a default value

参考:使用带有ngOptions的select并设置默认值

#5


0  

Just remove

只需删除

 ng-init="userselected = vm.data[0]"  

this init call from login.html

来自login.html的这个init调用

<div>
    <select ng-model="userselected"
            ng-options="option.name for option in vm.data">
    </select>
</div> 

and modify your controller as -

并将您的控制器修改为 -

 .controller('f',function($http,$scope){  // add $scope as a DI
    var l=this;
    $http.get('data.json').success(function(data){
      l.data=data;
      $scope.userselected = l.data[0];  // initalize or select first option
    })
  })

Hope this help!

希望这有帮助!

#1


0  

Can we load data before calling controller and loading the html file using resolve?

我们可以在调用控制器之前加载数据并使用resolve加载html文件吗?

Yes. The way to do that would be to resolve the dataset you want to expose onto your view before initialising the controller attached to said portion of the view.

是。这样做的方法是在初始化附加到视图的所述部分的控制器之前解析要在视图上公开的数据集。

I can think of three ways off of the top of my head;

我可以想到三个方面;

  • ui-router#resolve.
  • UI路由器#决心。
  • ngRoute#resolve.
  • ngRoute#决心。
  • defer compilation of the DOM attached to your controller.
  • 推迟编译附加到控制器的DOM。

ui-router#resolve

// state definition
.state('myState', function () {
  resolve: {
    dataset: function (Service) {
      return Service.getData();
    }
  },
  controller: 'Controller'
})
// controller definition
.controller('Controller', function (dataset) {
  this.dataset = dataset;
})

The resolved data will be available under the given name in the controller attached to the state definition (through the definition itself, or with a ng-controller at the root of your state template).

已解析的数据将在附加到状态定义的控制器中以给定名称提供(通过定义本身,或者在状态模板的根目录下使用ng-controller)。

ngRoute#resolve

// route definition
.when('/path', {
  resolve: {
    dataset: function (Service) {
      return Service.getData();
    }
  },
  controller: 'Controller'
})
// controller definition
.controller('Controller', function (dataset) {
  this.dataset = dataset;
})

Pretty much the exact same way as the ui-router example.

几乎与ui-router示例完全相同。

ngIf

Defer the rendering of your template, by waiting for the promise to resolve.

通过等待承诺解决来推迟模板的呈现。

.controller('outer', function ($timeout) {
  this.resolved = false;
  this.dataset  = [];

  $timeout(function () {
    this.resolved = true;
    this.dataset = [ {}, {} ];
  }.bind(this), 1500);
})
.controller('inner', function () {
  console.log('I just ran!');
})

<div ng-controller="outer as o">
  <div ng-controller="inner as i" ng-if="o.resolved">
    {{o.dataset}}
  </div>
</div>

jsfiddle of the last solution

jsfiddle的最后一个解决方案

#2


0  

Check it out. So with angular you should be binding your model with the HTML elements using $scope.

一探究竟。因此,对于angular,您应该使用$ scope将模型与HTML元素绑定。

http://plnkr.co/edit/dVI0MDC5k4AVSJAOMyy3?p=preview

http://plnkr.co/edit/dVI0MDC5k4AVSJAOMyy3?p=preview

The way I resolved this was to store your data to a scoped variable, and setting the init value to the first index in the array

我解决这个问题的方法是将数据存储到作用域变量,并将init值设置为数组中的第一个索引

controller('f',function($http, $scope){
    $scope.vm = null;
    $scope.userselected = null;
    $http.get('data.json').success(function(data){
      $scope.vm=data;
      $scope.userselected = $scope.vm[0];
    })
  })

And the changes to your HTML:

以及对HTML的更改:

    <select ng-model="userselected"
            ng-options="option.name for option in vm">
    </select>

#3


0  

Your problem is that vm.data is being populated asynchronously. When the view first loads and the ng-init is run, vm.data[0] is undefined, which is why it doesn't work. A quick fix is to add ng-if="vm.data" to the wrapper div so that the content within the ng-if is only added to the dom after vm.data is defined.

您的问题是vm.data是异步填充的。当视图首次加载并运行ng-init时,vm.data [0]未定义,这就是它不起作用的原因。快速解决方法是将ng-if =“vm.data”添加到包装器div中,以便ng-if中的内容仅在定义vm.data后添加到dom中。

Also, Julian's answer is definitely a better solution. ng-init is usually a bad way to initialize values - it is much preferred that you initialize them in a controller.

此外,朱利安的答案绝对是一个更好的解决方案。 ng-init通常是一种初始化值的坏方法 - 最好在控制器中初始化它们。

#4


0  

Here is a demo on how to set the default value in select option.

这是一个关于如何在select选项中设置默认值的演示。

Use: set the value using ng-model

使用:使用ng-model设置值

HTML:

HTML:

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-select-with-default-values-production</title>  

  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
  <script src="app.js"></script>

</head>
<body ng-app="defaultValueSelect">
  <div ng-controller="ExampleController">
  <form name="myForm">
    <label for="mySelect">Make a choice:</label>
    <select name="mySelect" id="mySelect"
      ng-options="option.name for option in data.availableOptions track by option.id"
      ng-model="data.selectedOption"></select>
  </form>
  <hr>
  <tt>option = {{data.selectedOption}}</tt><br/>
</div>
</body>
</html>

JS:

JS:

(function(angular) {
  'use strict';
angular.module('defaultValueSelect', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.data = {
     availableOptions: [
       {id: '1', name: 'Option A'},
       {id: '2', name: 'Option B'},
       {id: '3', name: 'Option C'}
     ],
     selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
     };
 }]);
})(window.angular);

Reference: Using select with ngOptions and setting a default value

参考:使用带有ngOptions的select并设置默认值

#5


0  

Just remove

只需删除

 ng-init="userselected = vm.data[0]"  

this init call from login.html

来自login.html的这个init调用

<div>
    <select ng-model="userselected"
            ng-options="option.name for option in vm.data">
    </select>
</div> 

and modify your controller as -

并将您的控制器修改为 -

 .controller('f',function($http,$scope){  // add $scope as a DI
    var l=this;
    $http.get('data.json').success(function(data){
      l.data=data;
      $scope.userselected = l.data[0];  // initalize or select first option
    })
  })

Hope this help!

希望这有帮助!