Updating ng-model within a directive that uses a template

后端 未结 2 1365
栀梦
栀梦 2021-01-01 21:40

I have a directive that is instantiated like this:


Inside the directive, the datepic

2条回答
  •  天命终不由人
    2021-01-01 22:09

    There are a few ways to do this..

    There is a function on the ctrl parameter of the linking function called .$setViewValue(valueHere) that you can use to set the value of whatever ngModel is referencing as well. It will do the work of setting things $dirty etc. There is also a property called .$viewValue you can use to get the current value. So you can set up a $watch on an isolate scope property to update the ngModel values.

    The more correct way to do this would still be in the linking function, but it would look like so:

    app.directive('myDirective', function() {
        restrict: 'E',
        require: 'ngModel',
        scope: {}, //isolate the scope
        template: '
    ' + '' + '' + '
    ', controller: function($scope) { }, link: function(scope, elem, attr, ctrl) { //get the value from ngModel scope.date = ctrl.$viewValue; //set the value of ngModel when the local date property changes scope.$watch('date', function(value) { if(ctrl.$viewValue != value) { ctrl.$setViewValue(value); } }); } });

提交回复
热议问题