ReferenceError:$ scope未在angularjs指令中定义

时间:2014-12-10 06:59:11

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

我尝试访问$scopeangularjs)控制器中的ionic framework时收到此错误

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中的值,并将文本框值设置为&#39;示例名称&#39;,但是当我点击保存按钮时,它会触发{{1}方法,但在里面,我没有recipeSave变量

而且我确实理解有很多同样错误的SO问题,我也检查了它们。但是大多数用户控制器直接绑定到视图,而不是作为指令。

我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

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

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
  }
}]);