使用ng-model的双向数据绑定失败

时间:2014-07-17 15:46:43

标签: angularjs angularjs-directive angularjs-scope

使用ng-model进行的双向数据绑定无效。

父指令模板:

<div class="form-group">
    <label>Company Phone</label>
    <input ng-model="formData.company_phone" type="phonenumber" class="form-control" placeholder="Company Phone">
</div>

儿童指令:

.directive('input', [function(){
    return: {
        restrict: 'E',
        require: '?ngModel',//right now this is binding to this directive scope, not a parent one
        link: function($scope, element, attr, ngModel){
            if (attr.type !== 'phonenumber') {
                return;
            }
        //some code to validate a phone number
        $scope.$apply(function () {
            //bind updated number, but I need this to reflect in the parent scope
            $scope[attr.ngModel] =  formattedNumber; 
}

1 个答案:

答案 0 :(得分:1)

我使用$parse来解决此问题:

.directive('input', ['$parse', function($parse){
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function(scope, element, attr, ngModel){
            var getter = $parse(attr.ngModel);
            var setter = getter.assign;

            if (attr.type !== 'phonenumber') {
                return;
            }
            //code that validated a phone number

            scope.$apply(function () {
                setter(scope, formattedNumber);
            });
         }
    }
}]);