无法在Angular中获取对象模型

时间:2015-06-25 06:23:08

标签: javascript angularjs

我正在尝试从我的控制器访问一个对象模型,但我总是不定义。

这是我的代码:

<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>

这是我的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
    }

});

这是我的模态控制器:

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',
        });

    }

});

如果我输入任何不超过10个字符长度的字符,计数器不会递减,那么也会出错。如果我输入10以上,它会减少。

1 个答案:

答案 0 :(得分:1)

据我所知,您的“注释”模型未定义,因为您的ng-model直接尝试访问它的属性。将此代码添加到顶部的控制器:

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