从输入字段捕获值

时间:2015-12-30 23:51:42

标签: angularjs html5 angularjs-directive

我试图从我的表单中的某个输入字段中获取值,但我的代码不起作用:

JavaScript的:

angular
    .module('myDirectives')
    .directive('pwMatch', matchPassword);

function matchPassword() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            var modelIt = attrs.pwMatch;
            var inputValue = attrs.modelIt;
            console.log(inputValue);
        }
    };
};

HTML:

<input name="telephone" type="number" value="223344455">
<div pw-match="form.telephone"></div>

2 个答案:

答案 0 :(得分:1)

如果您尝试获取输入值,请使用ng-model

<input ng-model="form.telephone" type="number" value="223344455">
<div pw-match input-name="form.telephone"></div>

如果您想使用属性上的名称在指令中获取该值,请在范围内使用$watch方法。

JS

angular.module('myDirectives',[])
.directive('pwMatch', function() {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.inputName, function(value) (
                var inputValue = value;
                console.log(inputValue);
            };
        }
    }
});

答案 1 :(得分:0)

 .module('myDirectives')

需要

 .module('myDirectives', [])

即使您没有依赖项,也必须拥有空数组。

另外,使用变量函数作为指令或其他东西是一个非常糟糕的主意,它会让你感到困惑。

这也有效,并且可能使您的应用程序更容易维护:

angular.module('myDirectives', [])
.directive('pwMatch', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            var modelIt = attrs.pwMatch;
            var inputValue = attrs.modelIt;
            console.log(inputValue);
        }
    }
});
相关问题