在我看来:
<div ng-controller="formCtrl">
<div class="alert alert-success" ng-show={{alert}}>"hey"</div>
</div>
我的表单:
<form name="myForm" ng-controller="formCtrl" ng-submit="submit()">...
在我的 Controller formCtrl 上,我有:
$scope.submit = function($scope) {
$http.post('/add', {brand: this.brand} ).success(function(data){
this.alert = true;
});
//this.alert(true); <-- also tried, did not work
};
我希望能够在提交表单时更新警告框。
因此:单击表单上的警报按钮 然后:提交表单 然后:“警报”会更新为成功或失败消息
我想我的范围都混淆了。不确定。
最佳答案
看不到您的所有代码,但我认为它存在多个问题,并且您对作用域在 JavaScript 中的工作原理缺乏基本的了解。我将尝试解释下面发生的事情,但您需要了解范围界定才能完全理解...我建议您阅读 http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/了解有关范围界定的更多信息。
首先,您不需要提交函数来接收变量。当您的提交电话甚至不接受时。
$scope.submit = function($scope) {
可以...
$scope.submit = function() {
因为你这样调用提交函数...
...ng-submit="submit()">...
此外,如果您将该输入参数命名为“$scope”,它将覆盖原始的 $scope 变量,从而使您无法在提交函数中访问它。
相反,您实际上可以访问 $scope 变量而无需将其实际传递给提交函数,因为它在 Controller 的范围内。基本上, Controller 中的任何函数都可以访问 $scope,而无需将其作为参数传递。所以简而言之,你的代码应该是这样的……
$scope.submit = function() {
$http.post('/add', {brand: this.brand} ).success(function(data){
$scope.alert = true;
});
};
关于javascript - 无法从 Angular JS 的 Controller 函数中访问 $scope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21420212/