【问题标题】:ng-click or ng-submit is not invoking controller methodng-click 或 ng-submit 未调用控制器方法
【发布时间】:2014-12-11 05:52:13
【问题描述】:

刚开始学习Angular JS,下载了Dan Wahlin's Customer Manager App 为了我的手。到目前为止,我已经尝试调用我的 Web API 来返回所有记录并与运行良好的 View 绑定。 现在我正在尝试添加一个带有提交按钮的文本框来搜索输入的文本,这似乎是 Angular 应用程序的非常基本的功能,但无法通过单击提交按钮调用控制器方法:

    <form ng-submit="getSearchResuls(id)">
        <input type="text" data-ng-model="id" class=" novalidate form-control" />
        <input type="submit" value="Search"  />
    </form>

我也试过了:

        <form >
        <input type="text" data-ng-model="id" class=" novalidate form-control" />
        <input type="submit" value="Search" onclick="getSearchResuls(id)" />
    </form>

两者都不适用于我的以下控制器定义 (函数 () {

var injectParams = ['$location', '$filter', '$window',
                    '$timeout', 'authService', 'dataService', 'modalService'];

 var CustomersController = function ($location, $filter, $window,
    $timeout, authService, dataService, modalService) {

function getSearchResuls(id) {
        dataService.getSearchResults(id, vm.currentPage - 1, vm.pageSize)
            .then(function (data) {
                vm.totalRecords = data.totalRecords;
                vm.customers = data.results;
                filterCustomers(''); //Trigger initial filter

                $timeout(function () {
                    vm.cardAnimationClass = ''; //Turn off animation since it won't keep up with filtering
                }, 1000);

            }, function (error) {
                $window.alert('Sorry, an error occurred: ' + error.data.message);
            });
    }
};

CustomersController.$inject = injectParams;

angular.module('customersApp').controller('CustomersController', CustomersController);

}());

我也尝试在 form 标签中添加 ng-controller,但仍然没有成功。 请问您的宝贵意见可以解决这个问题吗?

【问题讨论】:

    标签: javascript angularjs asp.net-web-api asp.net-web-api2


    【解决方案1】:

    函数getSearchResuls 需要添加到您的作用域中。所以,首先,确保'$scope' 被列为一个injectParams,然后包含$scope 作为你的CustomersController 的参数。然后做这样的事情:

    $scope.getSearchResuls = function (id) {
       //the rest of your code here
    }
    

    【讨论】:

    • 感谢您的回答,我在控制器中注入了“$scope”,然后将其包含在我的控制器中,例如 var CustomersController = function ($scope,$location, $filter, $window, $timeout, authService, dataService, modalService) { 然后定义了 getSearchResuls 方法,但是我得到了错误 ReferenceError: getSearchResuls is not defined ,有什么线索吗?
    • 我继续做了一个 jsfiddle。我怀疑您的代码可能存在其他错误。随意提供另一个 jsFiddle,我可以更好地查看您的所有代码。 jsfiddle.net/gsmk6f1w
    • 感谢 JsFiddle 链接,我搞砸了范围,this 还有一个愚蠢的错误,使用 onClick 而不是 ng-Click,请原谅我!
    • 现在新问题是我想在视图中访问范围变量 $scope.customers = data.results。我试图像
      很高兴看到 ngClick 正在工作。如果可能,请创建一个 jsfiddle。我注意到您缺少双引号,可能还有其他内容,但我无法从提供的摘录中看出。
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多