angularJS 和 ng-model 奇怪的行为

angularJS and ng-model strange behavior

问题很简单 - 为什么这样工作?

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>

两个指令之间的唯一区别是第二个模板用 'div' 包装。

但是一个有效,另一个无效。

真的 - 我不明白 - 为什么要开始工作。但确实如此。

问题是 ng-model 不适用于 div。

更改:

.directive('nogo', function() {
        return {
            replace:true,
            restrict: 'E',
            template: '<div><input type="text"></div>',            
        };
    });

.directive('nogo', function() {
    return {
        replace:true,
        restrict: 'E',
        template: '<div><input ng-model='test' type="text"></div>',            
    };
});

不要忘记从 <nogo>*remove ng-model*</nogo> 中删除 ng-model 它正在工作..

您的问题是您正在将模型应用于 <div>here is another question 以及有关此问题的更多信息。

在这种特殊情况下,您可以将绑定更改为模板以使其工作。

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>

也在 ng-model 文档上说:

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