【问题标题】:Angularjs custom directive getting viewValue as undefinedAngularjs自定义指令将viewValue设为未定义
【发布时间】:2015-11-24 07:52:12
【问题描述】:

本人是Angularjs的初学者,理解有误请指正。

首先,下面是我的代码。我正在尝试为输入验证创建一个自定义指令。

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    您的指令模板创建input type,并且您在另一个input 类型文本中使用此指令。您不能在input 中使用input

    您创建的指令应在div 或其他占位符中使用。如下所示。指令的另一个属性应该在模板中定义。

    <div drtooltip-message>
    

    【讨论】:

    • 请检查我有问题的更新。我正在尝试将该指令用作输入字段中的属性。
    【解决方案2】:

    您可以使用 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;
                    };   
                }
            };
    });
    

    希望有帮助

    【讨论】:

    • 请检查我有问题的更新。我正在尝试将该指令用作输入字段中的属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2014-06-24
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多