如何在指令中访问值

时间:2017-03-20 12:59:27

标签: angularjs angularjs-directive

我的指示如下:

directive('checkKey', function() {
        return {
            restrict: 'A',
            scope: {
                min: '='
            },
            link: function(scope, elem, attrs) {
                elem.bind('keypress', function(event) {
                   if (event.keyCode === 46 || event.keyCode === 45) {
                        event.preventDefault();
                        return false;
                    } else if (event.key < scope.min) {
                        event.preventDefault();
                        return false;
                    }
                });
            }
        }
    })

但我无法访问输入模型值...

2 个答案:

答案 0 :(得分:1)

您需要要求ngModel,然后将ngModelCtrl注入您的链接。该值将在ngModelCtrl中。

directive('checkKey', function() {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                min: '='
            },
            link: function(scope, elem, attrs, ngModelCtrl) {

                // this would give you the ngModel value also.
                var ngModelVal = $parse(attrs.ngModel);

                elem.bind('keypress', function(event) {
                   if (event.keyCode === 46 || event.keyCode === 45) {
                        event.preventDefault();
                        return false;
                    } else if (event.key < scope.min) {
                        event.preventDefault();
                        return false;
                    }
                });
            }
        }
    })

答案 1 :(得分:0)

您可以require指令中的ngModel控制器。您可以通过$setViewValue设置ngModel值,并通过$modelValue

访问该值
var myApp = angular.module('myApp',[]);

myApp.directive('myDirective', function($timeout) {
    return {
        restrict: 'EA',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            console.log("$modelValue", ngModel);
            ngModel.$render = function() {
                $timeout(function() {
                    ngModel.$setViewValue('I am updated');  
                }, 5000);                
            };
        }
    };
});

function MyCtrl($scope) {
    $scope.name = 'Vinoth';
}

http://jsfiddle.net/x7xb0w26/