我正在尝试根据性别生成随机的名字和姓氏并填写到表格中。我正在使用 Angular $http
并且总体上对 Angular 还很陌生。每次加载时都会出现此错误
Use of undefined constant firstName - assumed 'firstName'
我的观点:
@section('content')
<form ng-app="getNameApp" ng-controller="getNameController">
Male<input type="radio" ng-model="gender" value="male" name="gender" /><br />
Female<input type="radio" ng-model="gender" value="female" name="gender" /><br />
<input type="text" ng-model="{{ firstName }}" name="firstName" />
<input type="text" ng-if="{{ lastName }}" value="{{ lastName.body }}" name="lastName" />
<button ng-click="randomNameController()">Randomize</button>
</form>
@stop
我的JS
angular.module('getNameApp', [])
.controller('getNameController', getNameController);
function getNameController ($scope, $http) {
$scope.gender = 'male';
var randomName = $http({
url: '/randomName',
method: "GET",
params: {gender: $scope.gender}
});
randomName.success(function(data) {
$scope.firstName = data.firstName;
$scope.lastName = data.lastName;
});
randomName.error(function() {
document.write(randomName);
});
}
我的 Controller
public function randomName () {
$faker = Faker\Factory::create();
$gender = Input::get('gender');
if ($gender == 'male') {
$names = [
'firstName' => $faker->firstNameMale
];
} else {
$names = [
'firstName' => $faker->firstNameFemale
];
}
$names['lastName'] = $faker->lastName;
return $names;
}
编辑:我检查了检查元素的网络选项卡,它显示 createCharacter 出现 500 内部服务器错误。 (路由到页面)
最佳答案
我没有看到那种错误,但是你有一个问题,你正在尝试从 promise 中获取名字
randomName.success(function() {
$scope.firstName = randomName.firstName; //<-- Here randomName is a promise not data
$scope.lastName = randomName.lastName;
});
而是获取作为 success
回调的第一个参数的数据,
randomName.success(function(data) {
$scope.firstName = data.firstName;
$scope.lastName = data.lastName;
});
关于javascript - 将未定义常量与 Angular 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25437032/