【发布时间】: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/…