Mappan
Mappan

Reputation: 2617

Angular ng-model won't pass

I'm working on an app, and am trying to pass a string through ng-model like I do in other places. But this one always returns "undefined".

HTML:

<aside>
    <p>List of objs:</p>
    <ul>
        <li class="objList" ng-repeat="obj in objs">
            <a href="" class="roomLink" ng-click="hideBool2 = true">{{ obj.topic }}</a>
            <div class="appear" ng-show="hideBool2">
                <a href="" class="exit" ng-click="hideBool2 = false">X</a>
                <input class="uName" ng-model="passWo" placeholder="Password">
                <button class="btn btn-default" ng-click="connectTo(obj.info)">OK</button>
                <p ng-bind="message"></p>
            </div>
        </li>
    </ul>
</aside>

Controller function used:

    $scope.connectTo = function(rName) {
        alert($scope.rooms[rName].password + " " + $scope.passWo)
        if($scope.rooms[rName].password != "") {
            if($scope.rooms[rName].password == $scope.passWo) {
                socket.emit("joinroom", { room: rName, pass: $scope.passWo }, function(success, errorMessage) {});
                $location.path("/room/" + rName);
            }else{
                $scope.message = "Wrong password";
            }
        }else{
            alert($scope.rooms[rName].password);
        }
    }

but the $scope.passWo always returns undefined.

Everything else works in the code.

Any help would be appreciated.

Upvotes: 0

Views: 62

Answers (1)

Matt Way
Matt Way

Reputation: 33171

The problem is that the ng-model is assigning the value to its internal $scope. So when you call the connectTo function, it finds the $scope.connectTo in the controller scope, but the use of $scope.passWo, can't find the value, as ng-repeat creates a scope for each item.

The easiest way to overcome this (if you want to use a single scope value) is to create a container object inside the controller:

$scope.cont = { passWo: '' };

Then inside your view, use:

ng-model="cont.passWo"

This article might help you: http://jimhoskins.com/2012/12/14/nested-scopes-in-angularjs.html

Upvotes: 1

Related Questions