Neel
Neel

Reputation: 9890

I am unable to get $apply inside $watch to work

I have a directive for an upload file that communicates with the server and returns a scope.dbInsertId. I want to watch this and then update the ng-model with this value. I am unable to get it to work using $apply. Here is my code:

            scope.$watch('dbInsertId', function(newValue, oldValue) {
                if (newValue)
                    scope.$apply(function() {
                        scope.ngModel = scope.dbInsertId;
                    });
                    console.log("I see a data change!"); 
                    return ngModel.$modelValue;
            }, true);

Is my code wrong?

Upvotes: 0

Views: 1061

Answers (2)

KoIIIeY
KoIIIeY

Reputation: 558

My answer for your question

<div ng-app="app">
    <div ng-controller="MyController">

        <form name="someForm">
            <div this-directive ng-model="theModel"></div>
            <div>theModel='{{ theModel }}'</div>
        </form>

     </div>
</div>

var app = angular.module('app', []);
app.controller('MyController', function($scope,$rootScope,$log) {

    $scope.theModel = '';

    $scope.$watch('theModel',function(newVal,oldVal){
        $log.info('in *MyController* model value changed',newVal,oldVal);
    });
});

app.directive('thisDirective', function($compile, $timeout, $log) {

    return {
        scope: {
            ngModel: '='
        },
        require: 'ngModel',
        template: '<input type="text" ng-model="ngModel" /><div child-directive ng-model="ngModel"></div>',

        link: function(scope, element, attrs, ngModel) {

        }, // end link
    } // end return

});

app.directive('childDirective', function($compile, $timeout, $log) {
    return {
        scope: {
            ngModel: '='
        },
        template: '<input type="text" ng-model="ngModel" />',
        require: 'ngModel',

        link: function(scope, element, attrs, ngModel) {

        },

    } // end return
});

jsfiddle.net/dXL4w/3

Upvotes: 2

Idkt
Idkt

Reputation: 2996

You need scope:

scope.$watch('dbInsertId', function(newValue, oldValue, scope) { // here
    if (newValue)
        scope.$apply(function() {
            scope.ngModel = scope.dbInsertId;
        });
        console.log("I see a data change!"); 
        return ngModel.$modelValue;
}, true);

Upvotes: 1

Related Questions