Angular JS数据没有从视图绑定到模型

Angular JS data is not binding from the view to the model

本文关键字:视图 绑定 模型 JS 数据 Angular      更新时间:2023-09-26

我遇到的问题是,从视图输入的文本字段没有绑定到控制器。

以下是视图片段:

<md-dialog-content ng-if="mode=='addSentence'" class="sticky-container">
    <md-input-container>
        <label for="sentence-text">Enter the sentence to be corrected</label>
        <input ng-model="theSentence" name="sentence-text"/>
    </md-input-container>
    <span flex>{{ error }}</span>
    <md-button class="primary" style="float:right;" aria-label="Save" ng-click="saveNewSentence()">Save</md-button>
</md-dialog-content>

这是控制器的功能,应该处理输入:

function ViewSentenceController($scope, $rootScope, $mdDialog) {
    $scope.mode = mode;
    $scope.user = user;
    $scope.theSentence = null;
    $scope.saveNewSentence = function() {
        console.log($scope.theSentence);
    }
    $scope.cancel = function() { $mdDialog.hide(); }
}

当调用saveNewSentence()时,它会将null记录到控制台,即使我在文本字段中有输入。

我肯定我错过了什么,我看不见,但我在这个简单的问题上花了太多时间,所以提前感谢你的帮助!

您的对话框拥有自己的$scope。因此:

 <input ng-model="$parent.theSentence" name="sentence-text"/>
    </md-input-container>

请在md对话框选项中设置'preserveScope:true'或。。我不确定,但试着把你的ng模型改为ex:"dialogObj.theSentence",并像这样阅读console.log($scope.dialogObj.theSentence);

如果你能分享一个完整代码块的js fiddle,我本可以更好地帮助你。但下面是一个例子,在这个例子中,我最初创建了两个空集的输入字段,然后我不断更新我的ng模型。

<body data-ng-app="formApp">
<div data-ng-controller="FormCtrl">
    <p>
        Name of Topic: <input type="text" data-ng-model="formData.title" placeholder="enter a title" />
    </p>
    Subscribers:
    <button data-ng-click="addSubscriber()">Add subscriber</button>
    <table>
        <tr>
            <th>Name</th>
            <th>Email</th>
        </tr>
        <tr data-ng-repeat="subscriber in formData.subscribers">
            <td><input type="text" data-ng-model="subscriber.name" placeholder="enter name" /></td>
            <td><input type="text" data-ng-model="subscriber.email" placeholder="enter email" /></td>
        </tr>
    </table>
    <hr style="margin:1em 0;" />
    <p>
        <em>Debug info</em>: {{ formData }}
    </p>
</div>

JS如下所示。

(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
    $scope.formData = {};
    $scope.formData.subscribers = [
        { name: null, email: null }
    ];
    $scope.addSubscriber = function() {
        $scope.formData.subscribers.push({ name: null, email: null });
    };
});
})(); 

如果这有帮助,请告诉我。

我已经在某种程度上解决了这个问题,通过将"binded"数据作为函数的参数传递,而不是让Angular将来自我称为saveNewSentence()的文本字段的数据与传递给它的theSentence参数绑定,例如:saveNewSentence(theSentence)。它奏效了。对我来说似乎是一个廉价的把戏,但是:

如果它很愚蠢并且有效,那么它就不是愚蠢的

希望这能帮助其他有类似问题的困惑灵魂。