【问题标题】:Materialize select isn't updated when model is changed using angular and ng-model使用 Angular 和 ng-model 更改模型时,物化选择不会更新
【发布时间】:2018-03-02 20:19:25
【问题描述】:

所以我使用 Materialize css 和 Angular js..

当我更改模型值时选择不会更新(如果我从该示例中删除具体化,一切正常)..

当我添加 materialize js 时,绑定似乎完全被破坏了。也许有人已经以某种方式解决了这个问题。

<div class="container" ng-app="App">
  <form ng-controller="Ctrl">
    <div class="row">
      <div class="col s12 input-field">
        <select name="selectInput" ng-model="object.select">
          <option value="1">Option 1</option>
          <option value="2">Option 2</option>
        </select>
       <label for="selectInput">Test select</label>
     </div>
  </div>
   <div class="row">
     <button class="btn" type="button" ng-click="click1()">
        Test 1
     </button>
    </div>
    <div class="row">
      <button class="btn" type="button" ng-click="click2()">
       Test 2
     </button>
    </div>
    <div>
      {{object.select}}
    </div>
  </form>
</div>

CSS:

angular.module('App', [])
  .controller("Ctrl", ['$scope', function($scope) {
    $scope.object = {};
    $scope.object.select = "1";

    $scope.click1 = function() {
      $scope.object.select = "1";
    }
    $scope.click2 = function() {
      $scope.object.select = "2";
    }
    $('select').material_select();
  }]);

Here is a fiddle

【问题讨论】:

  • 我想我找到了解决方法.. 是调用 $('select').val(optionValue) 然后 $('select').material_select().. 但无论如何这是一个错误绑定不起作用:(

标签: javascript angularjs materialize


【解决方案1】:

您应该在刷新选择值后调用 M.FormSelect.init,但在 setTimeout 内调用它以确保值已更新。

例如:

import * as M from 'materialize-css';

setCities(cities) {

   this.cities= cities

   setTimeout(() => { 
      M.FormSelect.init(document.querySelectorAll('#cities'), {}) 
   }, 0)

}
<select id="cities" class="validate" [disabled]="!cities" name="cities"  [(ngModel)]="client.adress.city.id">
   <option value="" disabled selected>Select a city</option>
   <option *ngFor="let city of cities" value="{{city.id}}">{{city.name}}</option>
</select>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多