访问控制器中的 angularjs 文本框值

accessing angularjs textbox value in a controller

我正在尝试学习 AngularJS 并需要帮助以在调用 http 服务时在单击按钮后传递用户输入的文本框文本值以附加到字符串 url 值。

我正在尝试以下列方式添加,但它在附加 URl 和用户从文本框中输入的文本时显示未定义的值。

这是我的 HtmlPage1.html

              <form ng-submit="abc(inputValue)">
                    <input type="text" name="name" ng-model="inputValue" />
                    <button type="submit">Test</button>
                </form>

和我的脚本文件Script.js

           var app = angular.module("repos", [])
            .controller("reposController", function ($scope, $http, $log) {
                $scope.inputValue = null;
                $scope.abc = function (value) {
                    $scope.inputValue = value;
                };

                $http({
                    method:'GET',
                    url:     'https://api.github.com/users/'+$scope.inputValue+'/repos'
                })
                        .then(function (response) {
                            $scope.repos = response.data;
                            $log.info(response);
                        });
            });

任何人都可以在这方面帮助我如何获得用户输入的附加到 URL 的正确值?

提前致谢。

请记住,由于 2 路绑定,您的控制器上有代码。

您将为模型设置一个对象。稍后您可以使用它们来提交数据。

为了让你明白我要解释的内容,我做了一个例子,希望对你有所帮助

在您的代码中:
在输入标签上设置 ng-model

<input type="text" name="name" ng-model="vm.data.inputValue" />

在你的控制器上让它可用,就像我的例子一样

   vm.data ={};  

然后使用一个函数使用 ng-click 发送它。

<button type="submit" ng-click="vm.submit()">Test</button>

我相信还有更多方法可以做到这一点。

我不太会解释,所以我举了个例子,希望对你有帮助: https://jsfiddle.net/moplin/r0vda86d/

  • 我的示例基本相同,但我不喜欢使用 $scope。

在您输入任何值之前拨打您的电话。为了用 inputValue 调用 API,请将 get 调用放在单击按钮内。

此外,您不必将 inputValue 传递到 HTML 的函数中,Angular 的 2 种方式绑定将为您完成这项工作。

例如: HTML

<form ng-submit="abc()">
     <input type="text" name="name" ng-model="inputValue" />
     <button type="submit">Test</button>
</form>

JS:

    var app = angular.module("repos", [])
                .controller("reposController", function ($scope, $http, $log) {
                    $scope.inputValue = null;
                    $scope.abc = function () {
                        $log.info($scope.inputValue) // you will have your updated value here
                        $http({
                        method:'GET',
                        url:     'https://api.github.com/users/'+$scope.inputValue+'/repos'
                    })
                    .then(function (response) {
                         $scope.repos = response.data;
                         $log.info(response);
                     });
                });
 };

希望对您有所帮助。