Or A
Or A

Reputation: 1789

why my ng-model doesn't bind?

I have the following html:

<form ng-submit="addPath()">
                <input type="text" ng-model="newPathText"  style="width: 500px;" placeholder="Enter a local or network folder location (e.g., K:\documents\new-york)">
                <input class="btn-primary" type="submit" value="add" style="margin-bottom: 10px">
            </form>

and the js code behind:

 $scope.addPath = function() {
        $scope.watchedFolders.push($scope.newPathText);
        apiService.addScanPath($scope.newPathText)
        $scope.newPathText= '';
    };

however, when i debug it and the addPath() is being called, i see that '$scope.newPathText' is always coming empty ('')...am i missing anything here?

Thanks

Upvotes: 0

Views: 1159

Answers (1)

Michael Benford
Michael Benford

Reputation: 14114

You shouldn't data bind your views to primitive types because of the prototypical nature of scopes. What's probably happening in your case is that your view is bound to a child scope which is different from the controller scope. Try changing your model to something like this:

$scope.newPath = { text: ''};

and then bind your view to it:

<input type="text" ng-model="newPath.text" ... >

That will ensure your view is bound to the correct scope.

This issue with primitives can be avoided by following a simple guideline: always have a . (dot) in your ng-model attributes. This post has valuable information on that matter.

Upvotes: 6

Related Questions