更改Angular模板时执行jQuery语句的问题

Problems executing jQuery statement when changing Angular template

本文关键字:jQuery 语句 问题 执行 Angular 更改      更新时间:2023-09-26

我正在开发一个单页应用程序,它有两个视图:主页和仪表板。

home状态有一个搜索表单。提交表单时,使用$window.location.assign('/#/dashboard');加载仪表板视图。

当从搜索中加载仪表板视图时,我需要自动将选择框值设置为0。我有代码做到这一点,但出于某种原因,它是不执行当页面加载…我认为这与Angular在加载页面时添加新的"select"DOM元素有关。

仪表板视图
  <div ng-controller="MainCtrl">
    <!-- list all lists -->
    <select id="list-select" class="list-select" ng-model="list" ng-options="list as list.title for list in lists">
        <option value="">Select List</option>
        <!-- when the page loads from search, this will be added...
        <option value="0">search</option>
        -->
    </select>
    <!-- end list -->
    <hr class="dash">
      <!-- words in selected list -->
      <ol ng-model="list.words">
        <li ng-repeat="word in list.words" id="word-{{word.id}}">
          <p>{{ word.title }}</p>
        </li>
      </ol>
    <!-- end words -->
</div>

main.js

$("#list-select").val("0");

请帮忙!

这里有一个非常相似的问题:如何使用ng-option来设置select element

的默认值

与其使用jQuery来设置选择列表的默认值,不如使用angular的方法:

<div ng-controller="yourController">
    <select ng-model="prop.value" ng-options="v for v in prop.values">
    </select>
</div>
yourApp.controller('yourController', ['$scope', '$http', function($scope, $http) {
    $scope.prop = { 
        value: 0, 
        values: []
    };
    // not the best way...
    $.getJSON('yourURL', function(data) {
        $scope.prop.values = data;
        $scope.$apply(); // you need to call this
    });
    // the better way
    $http.get('yourURL').success(function(data) {
        $scope.prop.values = data;
    }).error(function(error) {});
}]);

一般来说,在控制器中操作DOM是不好的做法。当模型更新时,你所做的更改将无法保持,并且它可能会在你的控制器逻辑中导致许多问题。

相反,您需要操作视图中使用的变量。在本例中,您可以在填充列表数组之后在控制器中执行以下操作:

$scope.lists.splice(0,0,{ value: 0, title: 'search' });

我只是在寻找一种方法来为选择框设置默认值。

基于这个答案,我能够使用ng-init完成这个任务。

   <!-- list all lists -->
  <select ng-model="list" ng-init="list = lists[0]" ng-options="list as list.title for list in lists">
      <option value="">Select List</option>
  </select>
  <!-- end list -->

将选择框的值设置为"0"。

感谢所有的帮助和提示,我会把这个标记为正确答案。