[英]Not able to access $scope variable from within a controller function in Angular JS
在我看来:
<div ng-controller="formCtrl">
<div class="alert alert-success" ng-show={{alert}}>"hey"</div>
</div>
我的表格:
<form name="myForm" ng-controller="formCtrl" ng-submit="submit()">...
在我的控制器上,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 /了解有关范围界定的更多信息。
首先,您不需要Submit函数来接受变量。 当您的提交呼叫什至不接一个。
$scope.submit = function($scope) {
可...
$scope.submit = function() {
因为您这样调用了commit函数...
...ng-submit="submit()">...
另外,如果将输入参数命名为“ $ scope”,它将覆盖原始的$ scope变量,导致您无法在Submit函数中访问它。
相反,您实际上可以访问$ scope变量,而无需实际将其传递给Submit函数,因为它在控制器的范围内。 基本上,控制器中的任何函数都可以访问$ scope,而不必将其作为参数传递。 简而言之,您的代码应如下所示:
$scope.submit = function() {
$http.post('/add', {brand: this.brand} ).success(function(data){
$scope.alert = true;
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.