通过参数直接访问变量 - 创建泛型函数

时间:2013-01-30 06:05:26

标签: angularjs pug

我正在尝试实现一种通用的剩余功能。我的表单中有很多字段,例如:名称地址。这些字段的字符大小有限制,我的目标是制作一个通用函数来限制它到达时的大小。所以我制作了一个有效的示例函数:

首页在页面上:

label(for='name') Name {{remaining()}} of {{totalChars}}

其次,处理它的代码:

$scope.totalChars = 10;

$scope.remaining = function() {
    var count = 0;

if ($scope.mName) {
    count = $scope.mName.length;

    if (count > $scope.totalChars) {
        $scope.mName = $scope.mName.trim().substr(0, $scope.mName.length - 1);
        count = $scope.mName.length;
    }
}

return count;

    //return calculateChars($scope.mName, $scope.totalChars);
};

当我在名称字段中输入一些输入值时,角度也会在达到10个字符时停止输入。但我已经重新设计了以通用方式转换它的功能,并尝试将它用于我想要的任何字段,但是没有按预期工作:

$scope.totalChars = 10;

$scope.remaining = function() {
    return calculateChars($scope.mName, $scope.totalChars);
};

...

function calculateChars(obj, size) {
    var count = 0;

    if (obj && obj !== 'undefined') {
        count = obj.length;

        if (count > size) {
            $scope.obj = obj.trim().substr(0, obj.length - 1);
            console.log('Result: ' + $scope.obj);
            count = obj.length;
        }
    }

    return count;
}

calculateChars工作偏好,问题是$scope.obj = obj.trim().substr(0, obj.length - 1);因为angularjs不知道“obj”是什么,并且在达到10个字符时不会停止输入,即使正确计算数量。

我不知道如何让第一种方法适用于任何情况,不会出现任何我希望的任何文本字段的代码。

提前致谢!

1 个答案:

答案 0 :(得分:1)

听起来你正在寻找指令。这是一个名为remaining的指令示例,给定模型和“最大长度”属性,显示剩余的字符数。它还可以防止用户输入超过最大字符数的内容;这可以通过删除链接函数中if (remaining < 0)检查的第一个分支来删除。

app.directive('remaining', function() {
  return {
    template: "{{remaining}} of {{maxLen}}",
    scope: {
      maxLen: '@max',
      model: '=ngModel'
    },
    link: function(scope, elem, attrs) {
      scope.$watch('model', function(val) {
        if (val == null || val == undefined) return;
        var maxLen = parseInt(scope.maxLen, 10);
        var remaining = maxLen - val.length;
        if (remaining < 0)
          scope.model = val.substr(0, maxLen);
        else
          scope.remaining = remaining;
      });
    }
  };
});

这是一个jsFiddle演示:http://jsfiddle.net/BinaryMuse/JanZm/。注意我正在使用AngularJS的1.1.x版来访问ngTrim指令,该指令告诉Angular不要剥离文本字段中的空格。