AngularJS指令$ scope未定义

时间:2016-02-08 19:05:01

标签: angularjs angularjs-directive angularjs-ng-repeat

我有以下指令。当我触发open函数并进入调试器时,我在控制台中收到Uncaught ReferenceError: $scope is not defined(…)的错误消息。

$scope.open未定义时如何调用$scope

app.directive('photo', ['$http', 'modal', function($http, modal) {
    return {
        replace: true,
        templateUrl: '/assets/photo.html',
        transclude: false,
        scope: {
            result: '=',
            index: '@'
        },
        controller: ['$scope', '$http', 'modal', function($scope, $http, modal) {
            $scope.prev = $scope.index - 1;
            $scope.open = function() {
                debugger;
            };
        }]
    }
}]);

这是我的DOM:

<div ng-repeat="r in results" photo result="r" index="$index"></div>

如果我在console.log($scope)函数之前插入open,然后再在该函数的debugger之前插入,我会得到以下结果。左边是调用open之前,右边是调用open之后。 enter image description here

5 个答案:

答案 0 :(得分:3)

您在指令定义中注入$httpmodal(就像您一样),不需要在控制器函数中执行:

controller: function($scope) {
        $scope.prev = $scope.index - 1;
        $scope.open = function() {
            debugger;
        };
    }

答案 1 :(得分:1)

尝试在$scope中添加使用$scope.open的语句。由于您未使用Chrome浏览器$scope,Chrome可能会优化$scope.open

$scope.open = function() {
  console.log($scope);
  debugger; //now you should see $scope.
};

答案 2 :(得分:0)

这应该有效:

app.directive('photo', ['$http', 'modal', function($http, modal) {
return {
    replace: true,
    templateUrl: '/assets/photo.html',
    transclude: false,
    scope: {
        result: '=',
        index: '@'
    },
    controller: function($scope, $http, modal) {
        $scope.prev = $scope.index - 1;
        $scope.open = function() {
            debugger;
        };
    }
}
}]);

答案 3 :(得分:0)

您需要在顶部定义$ Scope,即:         app.directive('photo',['$ http','$ Scope','modal',函数($ http,$ Scope,modal)

它现在可以正常工作了。

答案 4 :(得分:0)

它为我工作

var app = angular.module("moduleTest",[]);
app.directive("testDirective",function(){
    return {
        restrict: "A",
        scope: true,
        link: function(scope, element){
           //code
           //and $scope is scope
        }
    }   
 });