【问题标题】:Not able to access $scope variable from within a controller function in Angular JS无法从 Angular JS 的控制器函数中访问 $scope 变量
【发布时间】:2014-01-29 01:13:38
【问题描述】:

在我的观点中:

<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 ruby-on-rails ruby scope


    【解决方案1】:

    看不到您的所有代码,但我认为它存在多个问题,并且您对 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 变量,而无需实际将其传递给提交函数,因为它在控制器的范围内。基本上,控制器中的任何函数都可以访问 $scope 而无需将其作为参数传递。所以简而言之,你的代码应该是这样的......

    $scope.submit = function() {
    
         $http.post('/add', {brand: this.brand} ).success(function(data){
             $scope.alert = true;
          });
      };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多