AngularJS选择框设置文档就绪时的默认选定值

时间:2016-12-01 06:11:42

标签: javascript html angularjs

在Document ready事件中设置下拉列表的模型值时,我遇到了一个奇怪的问题。我希望在页面加载时选择Option4,但是当我按照以下方式执行操作时,这似乎并没有反映在我的视图中。请参阅以下代码......

HTML

<select ng-model="search_for" class="form-control" id="search_for">
                    <option value="">-Search For-</option>
                    <option value="1">Option1</option>
                    <option value="2">Option2</option>
                    <option value="3">Option3</option>
                    <option value="4">Option4</option>
</select> 

JS

angular.element(document).ready(function () {
$scope.search_for = 1;
}

即使我在html中{{search_for}},它也证明模型值不是通过显示任何内容来设置,而是显示下拉值更改时的值。

我做错了什么?。

谢谢。

2 个答案:

答案 0 :(得分:4)

而不是在document.ready上添加{}添加controller,因为控制器在视图之前加载,模型值会被反映

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select ng-model="search_for" class="form-control" id="search_for">
                    <option value="">-Search For-</option>
                    <option value="1">Option1</option>
                    <option value="2">Option2</option>
                    <option value="3">Option3</option>
                    <option value="4">Option4</option>
</select> 

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.search_for = "2";
    
});
</script>

</body>
</html>

请运行以上代码段

Here is a working Demo

答案 1 :(得分:1)

您需要为应用设置ng-app和ng-controller,而不使用 document.ready

var app = angular.module('DemoApp', [])
app.controller('akuaController', function($scope) {
 $scope.search_for = "1";
  
});
<head>
  <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
  <link rel="stylesheet" href="style.css" />
</head>

<body ng-app="DemoApp"    ng-controller="akuaController">
  
  
  <select ng-model="search_for" class="form-control" id="search_for">
    <option value="">-Search For-</option>
    <option value="1">Option1</option>
    <option value="2">Option2</option>
    <option value="3">Option3</option>
    <option value="4">Option4</option>
  </select>
  

 </body>

</html>