Search code examples
angularjsangular-ngmodel

angularJS and ng-model strange behavior


Question is simple - why this work like this work?

angular.module('test1', [])
    .directive('myDir', function() {
        return {
            replace:true,
            restrict: 'E',
            template: '<input type="text">',            
        };
    }).directive('nogo', function() {
        return {
            replace:true,
            restrict: 'E',
            template: '<div><input type="text"></div>',            
        };
    });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="test1">
    <my-dir ng-model="test"></my-dir>
    <nogo ng-model="test"></nogo>
    <input type="text" ng-model="test"/>
</body>

The only difference between two directive is that template for second wrapped with 'div'.

But one work, another doesn't.

Really - I don't understand - why working one is on. But it is.


Solution

  • Your problem here is that you are applying the model to the <div>, here is another question with more information about this problem.

    And in this particular case you can change the bind into the template in order to make it work.

    angular.module('test1', [])
        .directive('myDir', function() {
            return {
                replace:true,
                restrict: 'E',
                template: '<input type="text">',            
            };
        }).directive('nogo', function() {
            return {
                replace:true,
                restrict: 'E',
                template: '<div><input type="text" ng-model="test"></div>',            
            };
        });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <body ng-app="test1">
        <my-dir ng-model="test"></my-dir>
        <nogo ng-model="test"></nogo>
        <input type="text" ng-model="test"/>
    </body>

    Also on the ng-model docs says:

    The ngModel directive binds an input,select, textarea (or custom form control)