Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

javascript - AngularJs - bind one ng-model to directive with two inputs

How to create a range directive which binds to one ng-model and outputs two input fields using a filter (already made). Essentially I've got one direction from model to input working, but the other side from input to model not. How to achieve this?

I've got this Html:

<div tu-range ng-model="arbitraymodel" />

And a model:

var arbitrarymodel = "10/22";

Side note; I created a filter to split those two values:
{{ feature.Value | split:'/':0}}

And this directive:

.directive('tuRange', function($compile) {
    return { 
        restrict: 'A',
        require: 'ngModel',
        scope: {
            feature: '=',
            tudisabled: '=',
            model: '=ngModel' // edited
        },
        template: '<input type="text" '+
               'ng-value="{{ model | split:'/':0}}" />'+ // edited to 'model'
             '-<input type="text" '+
               'ng-value="{{ model | split:'/':1}}" />', // edited to 'model'
        link: function(scope, element, attributes, ngModel) {

        }
    };
})
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct way (IMO) is to create a custom control as described here.

As an exercise, I implemented it in this fiddle: http://jsfiddle.net/6cn7y/

The code of the directive is (you may need to adapt some details):

app.directive("range", function() {
    var ID=0;

    function constructRangeString(from, to) {
        var result;
        if( !from && !to ) {
            result = null;
        }
        else if( from ) {
            result = from + "/" + (to || "");
        }
        else if( to ) {
            result = "/" + to;
        }
        return result;
    }

    return {
        require: "ngModel",
        restrict: "E",
        replace: true,
        scope: {
            name: "@"
        },
        template:
            '<div ng-form="{{ subFormName }}">' +
                '<input type="text" ng-model="from" class="range-from" />' +
                '<input type="text" ng-model="to" class="range-to" />' +
            '</div>',
        link: function(scope,elem,attrs,ngModel) {
            var re = /([0-9]+)/([0-9]+)/;

            if( scope.name ) {
                scope.subFormName = scope.name;
            }
            else {
                scope.subFormName = "_range" + ID;
                ID++;
            }

            ngModel.$render = function() {
                var result, from, to;
                result = re.exec(ngModel.$viewValue);
                if( result ) {
                    from = parseInt(result[1]);
                    to = parseInt(result[2]);
                }
                scope.from = from;
                scope.to = to;
            };

            scope.$watch("from", function(newval) {
                var result = constructRangeString(newval, scope.to);
                ngModel.$setViewValue(result);
            });
            scope.$watch("to", function(newval) {
                var result = constructRangeString(scope.from, newval);
                ngModel.$setViewValue(result);
            });
        }
    };
});

And its usage would be:

<range ng-model="ctrl.theRange" name="myRange" required="true"></range>

I doubt the filters will get you anywhere with this, as they do not do 2-way binding.


EDIT: Even though this solves the problem, I would suggest a slightly different approach. I would define the model of the range directive as an object:

{
    from: ...,
    to:   ...
}

This means that the output in the ctrl.theRange variable in the example would be an object like that of the above. If you really want the string format "from/to", add a parser/formatter in the ngModel pipelines, i.e. the constructRangeString() function. Using the parser/formatter, the ctrl.theRange variable gets the desired string format, while keeping the code more modularized (the constructRangeString() function is external to the directive) and more parameterized (the model is in a format that can easilly be processed and transformed).

And a proof of concept: http://jsfiddle.net/W99rX/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...