0

I want to build a directive for showing datepicker textboxes, i.e regular textboxes which have JQuery UI's datepicker used on them, so when the user clicks them, a datepicker box opens to let them pick the date, etc.

I want to bind this directive somehow to a property on my scope. E.g if it were a normal textbox and I did ng-model='myDate' then $scope.myDate would be updated if the user typed in a new date. In the same way, I want to bind this field from the directive so when the user picks a date, it updates the scope property its bound to.

The problem is, I want to display the directive using something like this:

<datepicker name='something' value='2013-07-20' model='myProperty' />

And have the directive replace it with the <input type="text" /> etc. So I can't use ng-model.

How else can I bind the model property to the directive so that it updates whenever the user changes it?

4

1 回答 1

2

看看这是不是你想要的:

HTML

<div ng-app="app" ng-controller="Ctrl">
    <foo model="property"></foo>
    <input type="text" ng-model="property">
</div>

Javascript

angular.module('app', [])
    .directive('foo', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: { model: '=' },
            template: '<input type="text" ng-model="model">'        
        };
    })
    .controller('Ctrl', function($scope) {
       $scope.property = 'Foobar'; 
    });

jsFiddle

为了使用ng-model而不是model,您需要将输入包装在容器标签中。这是另一个说明它的jsFiddle脚本。

最后, Angular UI Bootstrap中有一个日期选择器控件。也许它已经做了你需要的。

于 2013-08-08T03:54:40.100 回答