AngularJS / Material: why the expression is not ev

2019-07-09 10:47发布

问题:

I do not understand why the expression "{{isMultiple}}" is not evaluated in this code:

HTML:

<md-input-container style="width: 30%;">
   <label>{{label}}</label>
   <md-select ng-model="choice" multiple="{{isMultiple}}">
     <md-option value="1">Option 1</md-option>
     <md-option value="2">Option 2</md-option>
     <md-option value="3">Option 3</md-option>
   </md-select>
 </md-input-container>

JS:

angular.module('app', ['ngMaterial'])
    .controller('AppCtrl', AppCtrl);

function AppCtrl($scope) {

    $scope.isMultiple = false;
    $scope.choice = "";
    $scope.label = "MyLabel";
}

Full code on Plunker: https://plnkr.co/edit/a5yCLW?p=preview

The Dropdown control should NOT be multi-selectable in this example.

回答1:

It is not possible to pass an expression to the attribute multiple, according to the documentation:

However, one way around this is to create the md-select in the code - CodePen

Markup

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp">
<md-input-container id="myInputContainer" style="width: 30%;">
   <label>{{label}}</label>
 </md-input-container>
</div>

JS

angular.module('MyApp',['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngDialog'])

.controller('AppCtrl', function($scope, $element, $compile) {
  var myInputContainer = angular.element($element[0].querySelector('#myInputContainer')),
      mdSelect,
      mdSelectElement;

  $scope.options = [
    {value: 1, label: "Option 1"},
    {value: 2, label: "Option 2"},
    {value: 3, label: "Option 3"}
  ]
  $scope.isMultiple = false;
  $scope.choice = "";
  $scope.label = "MyLabel";

  mdSelect = "<md-select ng-model='choice' multiple='" + $scope.isMultiple + "'>" +
    "<md-option ng-repeat='option in options' value='{{option.value}}'>{{option.label}}</md-option>" +
    "</md-select>";
  mdSelectElement = angular.element(mdSelect);
  myInputContainer.append(mdSelectElement);
  $compile(myInputContainer)($scope);
});


回答2:

well if you could do

multiple="false"

then you won't get checkboxes but it work quiet simple user can select only one value as expected. checkbox means there could be more then one selection could be made.