AngularJS要求ngModel的多个指令

时间:2015-02-15 03:23:30

标签: javascript angularjs angularjs-directive angularjs-ng-model

这是我想要完成的jsfiddle example

我正在尝试构建美国电话号码输入,其中视图显示为(333)555-1212,但模型绑定到数字整数3335551212。​​

我的目的是向NgModelController添加自定义验证器,这就是我require: ng-model的原因;有没有隔离范围和NgModelController的更简单的解决方案,但我需要两者。

你会在控制台中看到一个立即错误:Error: Multiple directives [ngModel, ngModel] asking for 'ngModel' controller on: <input ng-model="user.mobile numeric" name="telephone" type="tel"> - 我以为我在这里使用了隔离范围......

2 个答案:

答案 0 :(得分:4)

感谢您寻找@ mimir137,但我似乎已经解决了它:

http://jsfiddle.net/hr121r18/8/

该指令使用的是replace: true,最终结构为:

<form ng-controller="FooCtrl" class="ng-scope">
    <p>Enter US phone number</p>
    <input ng-model="user.mobile numeric" name="telephone" type="tel">
</form>

模板和标记都需要ng-model,这导致了问题描述中的症状错误。删除后,它会导致此标记(请注意包装元素phone-number):

<form ng-controller="FooCtrl" class="ng-valid ng-scope ng-dirty ng-valid-parse" abineguid="BC0D9644F7434BBF80094FF6ABDF4418">
    <p>Enter US phone number</p>
    <phone-number ng-model="user.mobile" class="ng-untouched ng-valid ng-isolate-scope ng-dirty ng-valid-parse">
       <input ng-model="numeric" name="telephone" type="tel" class="ng-valid ng-dirty ng-touched">
    </phone-number>
</form>

但删除了$render所需的更改;传递给链接函数的elem现在为phone-number,因此您需要挖掘以获取其中的input并在其上设置值:

ngModel.$render = function () {
  elem.find('input').val($filter('phonenumber')(ngModel.$viewValue));
}; 

还有一些其他问题。还需要从观察者那里调用$render()

决赛:

var app = angular.module('myApp', []);

// i want to bind user.mobile to the numeric version of the number, e.g. 3335551212, but 
// display it in a formatted version of a us phone number (333) 555-1212
// i am trying to make the directive's scope.numeric to have two-way binding with the controller's
// $scope.user.mobile (using isolate scope, etc.).
app.controller('FooCtrl', function ($scope) {
    $scope.user = {
        mobile: 3335551212
    };
});

app.directive('phoneNumber', ['$filter', function ($filter) {
    return {
        restrict: 'E',
        template: '<input ng-model="numeric" name="telephone" type="tel">',
        require: 'ngModel',
        scope: {
            numeric: '=ngModel'
        },
        link: function (scope, elem, attrs, ngModel) {

            // update $viewValue on model change
            scope.$watch('numeric', function () {
                ngModel.$setViewValue(scope.numeric);
                ngModel.$render();
            });

            // $modelValue convert to $viewValue as (999) 999-9999
            ngModel.$formatters.push(function (modelValue) {
                return $filter('phonenumber')(String(modelValue).replace(/[^0-9]+/, ''));
            });

            // $viewValue back to model
            ngModel.$parsers.push(function (viewValue) {
                var n = viewValue;
                if (angular.isString(n)) {
                    n = parseInt(n.replace(/[^0-9]+/g, ''));
                }
                return n;
            });

            // render $viewValue through filter
            ngModel.$render = function () {
                elem.find('input').val($filter('phonenumber')(ngModel.$viewValue));
            };

        }
    };
}]);

app.filter('phonenumber', function () {
    return function (number) {
        if (!number) {
            return '';
        }
        number = String(number);
        var formattedNumber = number;
        var c = (number[0] === '1') ? '1 ' : '';
        number = number[0] === '1' ? number.slice(1) : number;

        var area = number.substring(0, 3),
            exchange = number.substring(3, 6),
            subscriber = number.substring(6, 10);

        if (exchange) {
            formattedNumber = (c + '(' + area + ') ' + exchange);
        }
        if (subscriber) {
            formattedNumber += ('-' + subscriber);
        }
        return formattedNumber;
    }
});

HTML

<form ng-controller="FooCtrl">
    <p>Enter US phone number</p>
    <phone-number ng-model='user.mobile'></phone-number>
</form>

答案 1 :(得分:0)

我创建了this fiddle,可以摆脱控制台中出现的大多数错误。希望这至少能够让你走上正轨。

我更改了模板,以便您可以看到过滤器实际正在运行。 它现在在文本框下面有纯文本的典型{{ngModel | FilterName}}。 唯一真正的问题是在文本框中显示它。我相信你没问题。我会在早上检查,以防你仍然对此有疑问。

编辑:好吧,看来你已经解决了。太棒了!