为什么闭包中定义的函数不可访问?

时间:2016-01-07 08:31:51

标签: javascript angularjs scope closures

为什么在指令和监视回调方法中无法访问闭包中定义的函数?可以访问在同一范围内定义的其他变量。

注意:如果我在指令回调或'_personname'方法中调用_link函数,则稍后可以访问它。

不确定出了什么问题。

    'use strict';

    define('directives/vkValidator', ['angular', 'directives/vkForm'], function(angular, vkForm) {

    var moduleName = 'mdlDrVkForm';

    var RE_NAME = /^[a-z][a-z\.\s]+?$/i;

    function _personname(val) {
        return RE_NAME.test(val);
    }
    var directiveNname = 'vkValidator';

    angular.module(moduleName).directive(directiveNname,
        function() {
            // _personname is inaccessible here. Showing undefined
            // But RE_NAME is accessible
            function _link(scope, ele, attrs, model) {
                scope.$watch(attrs.ngModel, function(newVal, oldVal) {
                    // _personname is inaccessible here as well
                    // But RE_NAME is accessible here as well
                    var fnTest = angular.isFunction('_' + attrs[directiveNname]),
                        isValid = fnTest ? fnTest(newVal) : false;

                    model.$setValidity(attrs[directiveNname], isValid);
                });
            }
            return {
                restrict: 'A',
                require: 'ngModel',
                link: _link
            };
        });
    return moduleName;
   });

0 个答案:

没有答案