【问题标题】:$ is not defined - jquery angular mixing$ 未定义 - jquery 角度混合
【发布时间】:2023-03-28 16:48:01
【问题描述】:

以前我使用 jQuery 开发所有项目,但最近开始使用 Angular。 我使用 Yeoman 生成器创建了一个 Angular 样板,并从中扩展了我的代码。

我将我的 ajax 表单发布 jQuery 代码翻译为以下 Angular 控制器。

'use strict';


angular.module('MyApp')
.controller('ShareformCtrl', function ($scope, $http) {
// create a blank object to hold our form information
// $scope will allow this to pass between controller and view
$scope.formData = {};

// process the form
$scope.processForm = function() {
    $http({
        method : 'POST',
        url : 'php/share_handling.php',
        data : $.param($scope.formData), // pass in data as strings
        headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
    })
    .success(function(data) {
        console.log(data);

        if (!data.success) {
            // if not successful, bind errors to error variables
            $scope.errorName = data.errors.name;
            $scope.errorSuperhero = data.errors.superheroAlias;
        } else {
            // if successful, bind success message to message
            $scope.message = data.message;
        }
    });
};
});

但是 jshint 在 $.param 上会失败

在我的索引中,我的 angular 和 jquery 实现如下:

<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>

所以 Angular 应该可以访问 $,但它没有或这里发生了其他事情。

【问题讨论】:

  • 谁在抛出错误 jshint 或浏览器?
  • 代码是否在浏览器中工作?我会避免混合使用 jQuery 和 Angular。
  • jshint 抛出这个错误
  • 您应该创建一个服务作为工厂来使用您的 $http POST 作为方法。然后在您的控制器中使用该方法。也不需要在你的成功中做一个 if else 声明。使用 .error() 作为您的错误代码。看看ng-book.com 会有很大帮助。
  • 不需要 $.param($scope.formData)。数据:$scope.formData 可以正常工作。如果你想传入 jQuery,使用 'value' 将 jQuery 注册到 Angular 注入器 stackoverflow.com/questions/27700519/papaparse-with-angular-js/…

标签: angularjs jshint


【解决方案1】:

告诉 JSHint 不要担心 $ 在根项目目录中创建 .jshintrc

{
  "globals": {
     "$": false
  }
}

Docs

【讨论】:

    【解决方案2】:

    在代码顶部添加以下注释以绕过 jshint 检查

    /* global $ */
    

    【讨论】:

    • 好的,这有助于构建它。在我的控制台中,我看到它正在发布,但没有发送任何数据。
    • 您确定$scope.formData 不是空对象吗?
    • console.log($scope.formData);正在打印 {},所以它在帖子上是空的:S
    • 是的,所以请检查一下为什么您的表单是空的:D
    • 噢!忘记了 ng-model,对不起大家 :P 谢谢你的帮助,总有一天我会爱上 Angular。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2014-03-07
    • 2021-04-20
    • 2015-05-22
    • 2016-01-07
    相关资源
    最近更新 更多