Jerielle
Jerielle

Reputation: 7520

Unable to get object model in Angular

I am trying to access an object model from my controller but I always get undefine.

Here's my code:

<script type="text/ng-template" id="myModalContent">

    <div ng-form="noteForm" ng-controller="NoteCtrl">

        <div class="modal-header">
            <h3 class="modal-title">Add New Note</h3>
        </div>
        <div class="modal-body">

            <!-- other text input here -->

            <div class="row">
                <div class="form-group col-md-12" ng-class="{'has-error': noteForm.c_message.$invalid && noteForm.c_message.$touched, 'has-success': !noteForm.c_message.$invalid }">
                    <label class="control-label">Message</label>
                    <textarea class="form-control" name="c_message" ng-model="note.c_message" ng-minlength="10" required></textarea>
                    <span style="color: red" ng-show="noteForm.c_message.$dirty && noteForm.c_message.$invalid">
                        <span ng-show="noteForm.c_message.$error.required">Message is required!</span>
                        <span ng-show="noteForm.c_message.$error.minlength">Message is should be less than 10 character!</span>
                    </span>
                    <p class="text-left">Number of characters left: <span ng-bind="word_count()">100</span></p> <!-- counter -->
                </div>
            </div>

        </div>
        <div class="modal-footer">
            <button class="btn btn-primary btn-sm" ng-disabled="noteForm.$invalid" ng-click="sendForm()">OK</button>
            <button class="btn btn-warning btn-sm" ng-click="cancel()">Cancel</button>
        </div>

    </div>

</script>

And here's my JS:

sampleApp.controller('NoteCtrl', function($scope) {


    $scope.sendForm = function () {
        console.log($scope.note); //ajax process
    }

    $scope.word_count = function() {
        return 100 - $scope.note.c_message.length; //return undefined
    }

});

Here's my controller for the modal:

sampleApp.controller('MainCtrl', function($scope, $modal, $log) {

    $scope.animationsEnabled = true;

    $scope.open = function open(size) {

        var modalInstance = $modal.open({
            animation: $scope.animationsEnabled,
            templateUrl: 'myModalContent',
            size: size,
            controller: 'ModalInstanceCtrl',
        });

    }

});

And there's also an error if I type any character that is not above 10 characters length the counter is not decrementing. It will decrement if I input above 10.

Upvotes: 0

Views: 62

Answers (1)

Reasurria
Reasurria

Reputation: 1848

As far as I can tell, your "note" model is undefined, because your ng-model directly tries to access a property of it. Add this code to the controller right at the top:

$scope.note = {c_message: ""};

Upvotes: 1

Related Questions