2016-01-21 74 views
2

我有,對焦點,我想打開一個對話框,其允許用戶執行復雜的選擇的輸入元件,然後將結果返回到輸入字段:更新模型值

<input ng-model="vm.requestType" ng-focus="vm.getMessageType($event)"> 
<input ng-model="vm.responseType" ng-focus="vm.getMessageType($event)"> 

控制器:

function getMessageType(event) { 

    $mdDialog.show({ 
     controller : 'MessageTypeController', 
     controllerAs : 'vm', 
     templateUrl : 'html/message-type.html', 
     locals : { type : event.target.value }, 
     bindToController: true 
     }).then(function(type) { 

     // this updates the DOM, but not the model 
     event.target.value = type; 

     // this works, but does not allow 
     // me to use this function generically for 
     // several different model fields 

     vm.requestType = type; 

     }, function(fail) { 
    }); 
} 

它的偉大工程,但只更新視圖,而不是模型。如果我直接更新模型值,它可以工作,但我不能使用多個<input> s的處理程序。

如何在事件處理程序中更新與<input>表單元素關聯的模型值?

+0

馬克你好,歡迎SO! – Ben

回答

0

我已經想出了一個解決方案。訣竅是獲得一個控制器,然後使用$ setViewValue和$ render();

<input ng-model="vm.requestType" ng-focus="vm.getMessageType($event)"> 
<input ng-model="vm.responseType" ng-focus="vm.getMessageType($event)"> 

    var controller = angular.element(event.srcElement).controller('ngModel'); 

    $mdDialog.show({ 
    controller : 'MessageTypeController', 
    controllerAs : 'vm', 
    templateUrl : 'html/message-type.html', 
    locals : { type : event.target.value }, 
    bindToController: true 
    }).then(function(type) { 

    controller.$setViewValue(type); 
    controller.$render(); 

    }, function(fail) { 

    }); 

這也可以被實現爲指令:

angular.module('app').directive('selectType', [ '$mdDialog', function($mdDialog) { 
    return { 
    restrict: 'A', 
    require: 'ngModel', 

    link: function(scope, element, attributes, controller) { 

     element.bind('focus', function() { 
     $mdDialog.show({ 
      controller : 'MessageTypeController', 
      controllerAs : 'vm', 
      templateUrl : 'html/message-type.html', 
      locals : { type : controller.$modelValue }, 
      bindToController: true 
     }).then(function(type) { 

      controller.$setViewValue(type); 
      controller.$render(); 

     }, function(fail) { 
     }); 

     }); 
    } 
    }; 
}]);