Angular 指令不会更新 ng-model

Angular Directive would not update ng-model

我似乎找不到在我的指令中更新我的 ng-model 的方法

我的指令是这样的

app.directive('DatepickerChanger', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: {
            Model: '=',
            startDate: '=',
            endDate: '=',
        },
        templateUrl: function(elem,attrs) {
            return '/AngularJS/Directives/msDatepickerTpl.html'
        },
        link: function (scope, element, attrs, ngModel) {  
               ngModel = new Date();
        }

    }
});

我是这样用的

 <DatepickerChanger ng-model="date" required></DatepickerChanger>

其中日期是另一个日期对象

如果我 console.log ng-model,我可以看到它正在改变它的值,但是从我调用指令的地方看不到它。任何人都知道我在做什么 worng

你用错了。这个 ngModel 是 controller。您的代码应如下所示:

link: function (scope, element, attrs, ngModel) {  
    ngModel.$setViewValue(new Date());
}

此外,该指令应称为 datepickerChanger 并在 html 中引用为 datepicker-changer

编辑:

例如,您想在更改输入后更新 ngModel。一种方法是使用 bind 函数来捕获输入字段的事件(我看不到你的模板,但我想它会有一个输入):

link: function (scope, element, attrs, ngModel) {  
    element.find('input').bind('change', function() {
       // Do something with this.value 
       ngModel.$setViewValue(newDate);
    });
}