如何将 ng-model 从指令传递到模板

How to pass ng-model from directive to template

给定以下指令定义

app.directive('myDirective', () => (
    {
        restrict: 'E'
        require: 'ngModel',
        template: '<div id='wrapper'><input ngChange="change" /></div>'
        scope: {change: '='},
        link: ...
    }
))

如果我这样用

<my-directive change="change" ng-model="myModel" />

如何将 ng-modelmy-directive 传递到 input

使用单向 < 绑定输入,$setViewValue 设置输出:

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        template:
            `<div id='wrapper'>
                 <input ng-change="change(inputValue)" ng-model="inputValue" />
             </div>`,                  
        scope: {inputValue: '<ngModel'},
        link: postLink              
    };
    function postLink(scope, elem, attrs, ngModel) {
        scope.change = function(value) {
            ngModel.$setViewValue(value);
        };
    }
})

用法:

<form name="form1">
    <my-directive name="item1" ng-model="myModel" ng-change="func1()">
    </my-directive>
</form>

ng-change 指令将由 ngModelController 自动添加。

AngularJS 框架会将 ngModelController API 作为 $scope.form1.item1.

的作用域

有关详细信息,请参阅