watch ng-model inside directive

Viewed 6768

I have the following directive:

directive('myInput', function() {
    return {
        restrict: 'AE',
        scope: {
            id: '@',
            label: '@',
            type: '@',
            value: '='
        },
        templateUrl: 'directives/dc-input.html',
        link: function(scope, element, attrs) {
            scope.disabled = attrs.hasOwnProperty('disabled');
            scope.required = attrs.hasOwnProperty('required');
            scope.pattern = attrs.pattern || '.*';
        }
    };
});

with the following template:

<div class="form-group">
    <label for="input-{{id}}" class="col-sm-2 control-label">{{label}}</label>
    <div class="col-sm-10" ng-switch on="type">
        <textarea ng-switch-when="textarea" ng-model="value" class="form-control" id="input-{{id}}" ng-disabled="disabled" ng-required="required"></textarea>
        <input ng-switch-default type="{{type}}" ng-model="value" class="form-control" id="input-{{id}}" ng-disabled="disabled" ng-required="required" pattern="{{pattern}}"/>
    </div>
</div>

It is used by this form:

<form ng-controller="UserDetailsCtrl" role="form" class="form-horizontal">
    <div ng-show="saved" class="alert alert-success">
        The user has been updated.
    </div>
    <my-input label="First name" value="user.firstName" id="firstName"></my-input>
    <my-input label="Last name" value="user.lastName" id="lastName"></my-input>
    <my-input label="Email" value="user.email" id="email" type="email" disabled></my-input>
    <my-input label="Password" value="user.password" id="password" type="password"></my-input>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <button ng-click="update()" class="btn btn-default">Save</button>
        </div>
    </div>
</form>

Which has this controller:

controller('UserDetailsCtrl', function($scope, $stateParams, User) {
    $scope.user = User.get({userId: $stateParams.id});
    /**
     * Update the current user in this scope.
     */
    $scope.update = function() {
        console.log($scope.user);
        $scope.user.$update({userId: $scope.user.id}).then(function(results) {
            $scope.saved = true;
        });
    };
}).

The form is rendered fine, but when I click the Save button, the user values are never updated.

How can I use the updated values from within the myInput directive in the controller scope?

2 Answers
Related