【问题标题】:ReferenceError: $scope is not defined from angularjs directiveReferenceError:$scope 不是从 angularjs 指令中定义的
【发布时间】:2017-12-06 05:58:14
【问题描述】:

我试图在我的 angularjs (ionic framework) 控制器中访问 $scope 时遇到此错误

ReferenceError: $scope is not defined

以下是我的设置

#directive recipe form
angular.module('directive.recipeForm',[])
  .directive('recipeForm', function(){
    return {
       restrict: 'E',
       controller: 'newRecipeCtrl',
       scope: false,
       templateUrl: 'templates/directives/recipe_form.html'
    }
  });

#templates/directives/recipe_form.html
<form ng-submit="recipeSave()">
  <input type='text' ng-model='recipeFormData.name' >  
  <input type="submit" id="submit" value="Submit" />
</form>

#recipe controller
angular.module('ft.controllers.newRecipe', [])
  .controller('newRecipeCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$http', 'Settings',function($scope, $rootScope, $ionicModal, $timeout, $http, Settings){

      $scope.recipeFormData={ name: 'sample name' };

      $scope.recipeSave = function(){
         // error from comes here
      }
    }]);

当表单加载时,它会正确访问$scope.recipeFormData 中的值并将文本框值设置为“样本名称”,但是当我单击保存按钮时,它会触发recipeSave 方法,但在里面我没有$scope 变量

而且我知道有很多 SO 问题都有相同的错误,我也检查了它们。但他们中的大多数用户控制器直接绑定到视图,而不是作为指令。

我可能做错了什么?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope ionic-framework


    【解决方案1】:

    我不确定这个错误的问题是什么。但在这种情况下(更改上下文变量:this、$scope 等),您可以将它们“保存”在 self 变量中:

    angular.module('ft.controllers.newRecipe', [])
      .controller('newRecipeCtrl', ['$scope', '$rootScope', '$ionicModal', '$timeout', '$http', 'Settings',function($scope, $rootScope, $ionicModal, $timeout, $http, Settings){
      var self = $scope;
      $scope.recipeFormData={ name: 'sample name' };
    
      $scope.recipeSave = function(){
         //here refer to self
      }
    }]);
    

    【讨论】:

    • 如果用户想更新函数内部的变量怎么办!
    • 如果用户想要更新变量属性,即 self.obj = sth,它可能会这样做。更改 self 本身的值(将其指向其他对象)没有意义。
    猜你喜欢
    • 2017-08-15
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    相关资源
    最近更新 更多