请原谅我的新生,但我无法理解。为什么单击提交表单时我的$ scope.new_prompt未定义?我可以看到变量在我输入时更新(在<p>{{new_prompt}}</p>
中)但是当我点击提交时,控制台记录'未定义'。
查看:
<div class="panel" ng-if="isAuthenticated()">
<div class="panel-body">
<h2 class="text-center">Add a prompt</h2>
<form method="post" ng-submit="submitPrompt()" name="promptForm">
<div class="form-group has-feedback">
<input class="form-control input-lg" type="text" name="prompt" ng-model="new_prompt" placeholder="Imagine if..." required autofocus>
<span class="ion-edit form-control-feedback"></span>
</div>
<p>{{new_prompt}}</p>
<button type="submit" ng-disabled="promptForm.$invalid" class="btn btn-lg btn-block btn-success">Add prompt</button>
</form>
</div>
</div>
控制器:
angular.module('Prompts')
.controller('HomeCtrl', ['$scope', '$auth', 'Prompt', '$alert', '$rootScope',
function($scope, $auth, Prompt, $alert, $rootScope) {
$scope.isAuthenticated = function() {
return $auth.isAuthenticated();
};
$scope.submitPrompt = function() {
console.log($scope.new_prompt);
Prompt.submitPrompt({
idea: $scope.new_prompt,
user: $rootScope.user
}).then(function() {
$alert({
content: 'Prompt has been added',
animation: 'fadeZoomFadeDown',
type: 'material',
duration: 3
});
});
};
$scope.stories = [{
prompt: 'Prompt 1',
author: 'blank',
upvotes: 0
}, {
prompt: 'Prompt 2',
author: 'klanb',
upvotes: 1
}, {
prompt: 'Prompt 3',
author: 'balbunk',
upvotes: 2
}, ];
}
]);
Ved的解决方案让它发挥作用。现在我不明白为什么必须这样做才有效:
<div class="panel">
<form ng-submit="printText()">
<input type="text" ng-model="justTest">
<button type="submit" class="btn"></button>
</form>
</div>
$scope.printText = function() {
console.log($scope.justTest)
};
编辑的工作示例:http://jsfiddle.net/fuczak/dLcLkycb/
问题在于ng-if指令。它创建了自己的子范围,这就是'new_prompt'所在的位置,而不是在父HomeCtrl范围内。
答案 0 :(得分:5)
有两种方法可以解决你的错误 案例1:将您的模型作为参数传递给函数:
<强> HTML:强>
<form method="post" ng-submit="submitPrompt(new_prompt)" name="promptForm">
<强>的JavaScript 强>:
$scope.submitPrompt = function(data) {
$scope.new_prompt=data;
console.log($scope.new_prompt);
Prompt.submitPrompt({
idea: $scope.new_prompt,
user: $rootScope.user
}).then(function() {
$alert({
content: 'Prompt has been added',
animation: 'fadeZoomFadeDown',
type: 'material',
duration: 3
});
});
};
案例2:在控制器中定义:scope.new_prompt= {},