1

選択 (ドロップダウン) を持つディレクティブを作成しようとしています。オプションの 1 つを選択すると、代わりに入力に変わります。

ドロップダウンには 1 ~ 12 の値と、「more...」という 1 つの値があり、ユーザーが「more...」を選択すると、選択は入力に変更されます。

問題は、変更がまったく発生しないことです。

私は人々が遊ぶために私のコードをプランカーに持っています: http://plnkr.co/edit/3SyFIYULDHMKgkJmtPtP?p=preview

var app = angular.module( 'myApp', [] ); // create app

app.controller( 'myCtrl', [ '$scope', function ( $scope ){ // simple controller
  $scope.value = '0';
  $scope.$watch('value', function(newValue, oldValue){
      console.log('watch fired in controller', newValue); // write the new value on change
  });
}]); 

app.directive('selectSwitch', function () { // the directive
  return {
  restrict: 'E', 
  template: '<div>'+  // template should know to switch between input and select
        '<input ng-model="myModel" ng-if="showInput" />'+ 
        '<select ng-model="myModel" ng-if="!showInput">'+
          '<option ng-repeat="value in selectSwitchValues" value="{{value}}">{{value}}<option>'+
        '<select>'+
      '<div>',
  scope: { 
      myModel: '=', // tie it to my model
  },
  link: function (scope, elem, attrs) {
    scope.selectSwitchValues = ['1','2','3','4','5','6','7','8','9','10','11','12','more...']; // values for select
    scope.showInput = false; 
    scope.$watch('myModel', function(newValue, oldValue){ // watch for changes in directive
      console.log('watch fired in directive');
      if(scope.myModel === "more..."){
        console.log("more");
        scope.showInput = true;
      }
      else {
        console.log(scope.myModel);
      }
    });
  }
  };
});

私も ng-switch でも試しましたが、うまくいきませんでした:

template: '<div ng-switch on="showInput">'+
    '<input ng-model="myModel" ng-switch-when="showInput">'+ 
    '<select ng-model="myModel" ng-switch-default>'+
        '<option ng-repeat="value in selectSwitchValues" value="{{value}}">{{value}}<option>'+
    '<select>'+
    '<div>',
4

2 に答える 2

1

@Anthony が ng-if の使用により既に指摘しているように、新しい子スコープが作成されたため、mymodel は更新されませんでした。そして、特定の目的のために常にコンパイルに ng-if を使用したい場合は、使用できます

$parent.myModel

テンプレートは以下の通り

template: '<div>'+
    '<input ng-model="$parent.myModel" ng-if="showInput">'+ 
      '<select ng-model="$parent.myModel" ng-if="!showInput" ng-options="value for value in selectSwitchValues">'+
      '<select>'+
  '<div>',

プランカー

于 2014-05-16T16:23:02.520 に答える