无法用Angular从HTML视图获取值到控制器.解决方案返回$scope变量undefined

Unable to get value from HTML view to controller using Angular. Solution returns $scope variable undefined

本文关键字:返回 解决方案 控制器 scope undefined 变量 Angular HTML 获取 视图      更新时间:2023-09-26

嗨,伙计们,我试图从使用angular ng-bind的文本字段中获得一些输入,并在控制器中访问它。目前,当我试图打印出来,我得到未定义。我肯定我的设置中遗漏了一些东西。

这是我的HTML
    <div class="text-center rounded-box" ng-app="AuthorisationTicketApp" ng-controller="LookupTicketController">
<form>
    <b>Please insert text:</b>
    <input type="text" name="text" ng-bind="text" />
</form>
<div class="lg-margin-top">
    <a href="#lookup-ticket" class="btn btn-lg btn-primary">Submit</a>
</div>

我的控制器

authorisationTicketApp.controller('LookupTicketController', ['$scope', 
function($scope) {
console.log('LookupTicketController .... called');
console.log('text' + $scope.text);
console.log('$scope ' + $scope);
}]);
我app.js

var authorisationTicketApp = angular.module('AuthorisationTicketApp', ['ngRoute']);
authorisationTicketApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/input-text', {
    templateUrl: contextPath + 'partials/input-text.html',
    controller: 'LookupTicketController'
}).
when('/lookup-ticket', {
        templateUrl: contextPath + 'partials/lookup-ticket.html',
        controller: 'LookupTicketController'
}).
otherwise({
    redirectTo: '/'
});

}]);

控制台输出

LookupTicketController .... called controllers.js:11:1
$ text undefined controllers.js:13:1
$scope [object Object]

在输入标签上使用ng-model而不是ng-bind。这将双向绑定到控制器中的值:

<input type="text" name="text" ng-model="text" />

这是来自文档:

使用控制器:*设置$scope对象的初始状态

不要用它来记录任何东西。它应该只包含业务逻辑。通过:

authorisationTicketApp.controller('LookupTicketController', ['$scope', 
function($scope) {
$scope.text = "test";
console.log('LookupTicketController .... called');
}]);

所有的控制器代码都是构造函数代码,并且text属性在构造时不存在。您需要在构造之后在其他地方调用一个可以使用$scope创建的方法。myMethod = function(){…},你应该能够引用$scope。里面的文本。用$scope初始化text属性也是一个很好的做法。Text = "在构造函数中。

这对我有用,请使用ng-model查看

<ion-modal-view>
    <ion-content>
        <input class="form-input" type="text" ng-model="test.relation"/>
        <button class="button button-bar button-positive" ng-click="answerswer()">Click Me</button>
    </ion-content>
</ion-modal-view> 

在您的控制器中,请将您的代码更新为:

$scope.test = {};
$scope.answer = function(){
    console.log($scope.test.relation);
}
如果您有任何疑问,请回复。
相关文章: