2015-11-24 18 views
1

我是Angularjs的初學者,所以如果我在理解上有誤,請糾正我。Angularjs自定義指令獲取viewValue爲undefined

首先,下面是我的代碼。我正在嘗試創建一個用於輸入驗證的自定義指令。

For example: 

<input drtooltip-message type="text" ng-minlegth="3"> //if the length of the input value is less than 3 a tooltip with custom message should be shown 
<input drtooltip-message type="text" ng-maxlegth="5">////if the length of the input value is greater than 5 a tooltip with custom message should be shown 

的Html

<div ng-app="validationApp" ng-controller="mainController"> 
    <input drtooltip-message type="text" name="name" class="form-control" ng-model="user.name" required tooltip="Tooltip on left" tooltip-placement="top" ng-minlength="5" ng-maxlength="8" > 
</div> 

的js

var validationApp = angular.module('validationApp', ['ui.bootstrap']); 

validationApp.controller('mainController', function($scope) { 

}); 

validationApp.directive('drtooltipMessage', function() { 
     return { 
      restrict: 'A', 
      template: '<input tooltip tooltip-placement="top" >', 
      replace: true, 
      require: 'ngModel', 
      link: function (scope, element, attrs, ctrl) { 
       ctrl.$parsers.push(function (viewValue) { 
        alert(viewValue);//always getting 'undefined' 
       } 
      } 
     }; 
}); 

我期待在輸入框中爲警戒值輸入的值,但我得到 '未定義'。

參考:What's the difference between ngModel.$modelValue and ngModel.$viewValue

回答

0

你的指令模板創建input type和你正在使用這個指令在另一input類型的文本。您不能在input內使用input

您創建的指令應該在div或其他佔位符中使用。如下所示。指令的另一個屬性應該在模板內部定義。

<div drtooltip-message> 
+0

請檢查我更新的問題。我試圖使用該指令作爲輸入字段中的屬性。 –

0

可以使用scope.ngModel雖然我會給你實現你的解決方案更好的方法讓當地在指令中的數據。

您的html可能看起來像這樣,只是添加您的相應屬性。

<input type="text" your-custom-text-field ng-model="textValue" ng-tooltip-max="5"> 

那麼你的指令看起來像這樣

validationApp.directive('yourCustomTextfield', function() { 
     return { 
      restrict: 'A', 
      template: '<input type="text" ng-model="model" ng-change="onChange()">', 
      replace: true, 
      require: 'ngModel', 
      scope: { 
       'ngToolTipMax': '=', 
       'ngModel': '=' 
      }, 
      link: function (scope, element, attrs) { 
       scope.onChange = function() { 
        // Your code goes here 

        // Update ng-model 
        scope.ngModel = scope.model; 
       }; 
      } 
     }; 
}); 

希望幫助

+0

請檢查我的更新是否有問題。我試圖使用該指令作爲輸入字段中的屬性。 –

+0

我更新了我的答案,請檢查希望有幫助。 – masterpreenz