Creating an AngularJS directive like ngModel for an array

Here is my problem: I have a control that I would like to use in AngularJS as an attribute directive (in fact, I have more, but let's just stick to one for now), like the model directive. I saw some examples in the documentation and tried to write my directive.

For example:

<input type="text" my-datepicker ng-model="appointment" />

This works fine, but the problem occurs when I try to work with array types. I debugged to find out what was causing the problem, and also looked for documentation after such problems.

Here is how I tried first:

.directive('myAnything', function(){
return {
    restrict: 'A',
    require: '?ngModel', // get a hold of NgModelController
    link: function (scope, element, attrs, ngModel) {
        if (!ngModel) return; // do nothing if no ng-model

        // initialize my control on the element
        // ...

        // Specify how UI should be updated
        ngModel.$render = render;

        // Listen for change events to enable binding
        element.on('change', function () {
            scope.$apply(read);
        });
        read();

        function read() {
            // read from controll, write to model
            // ngModel.$setViewValue([{text:'test'},{text:'test2'},{text:'test3'}]);
        }
        function render() {
            if (ngModel.$modelValue) {
                // update controller form model - render
                // ...
            }
        }
    }
};
});

AngularJS, , . , , angular , , . , : demo

, angular, , , ngModelController, , , ngModelController , .

myModelController, ngModelController, , $watch , true .

$scope.$watch(function myModelWatch() {
                var value = ngModelGet($scope);
                if (!angular.equals(ctrl.$modelValue, value)) {
                    ctrl.$modelValue = value;
                    ctrl.$render();
                }
                return ctrl.$modelValue;
            },
                function (newValue, oldValue) {
                    if (!angular.equals(newValue, oldValue)) {
                        ctrl.$render();
                    }
                },
                true
             );

, ngModel, ( ):

<input type="text" my-anything="listofappointments" />

, , .

<input type="text" my-anything="secondList" />

, , , angular, (), secondList ( , ).

: ? , , ? ... , , , angular? ?

! , , , , ( ng-), , .

, angular v1.0.8, , -, . ( )

!

+4
1

. -, , , ngModel. , , , , . , SO, , . Plunker, .

, , AngularJS. , . AngularJS " " . Plunker, , :

    scope: {
      names: '='
    }

:

    scope: {
      names: '=names'
    }

: " , ".

, , , .

0

All Articles