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?

1 Answer 1

2

See if this is what you want:

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

In order to use ng-model instead of model, you'll need to wrap the input in a container tag. Here's another jsFiddle script that illustrates it.

Finally, there's a date picker control in Angular UI Bootstrap. Perhaps it already does what you need.

Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't it be scope{value: '='} and then in the html: <datepicker value='dateProperty'>?
Sorry, I haven't picked good names. I'll update the code so it's less ambiguous.
Thanks. I built the directive using your answer as help, but I'm running into another issue. If you might be able to help here, I'd appreciate it: stackoverflow.com/questions/18139375/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.