AngularJS指令$ scope未定义

问题描述 投票:1回答:5

我有以下指令。当我触发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

angularjs angularjs-directive angularjs-ng-repeat
5个回答
3
投票

你在指令定义中注入了$httpmodal(正如你所做的那样),不需要在控制器函数中,只需执行:

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

1
投票

尝试添加在$scope中使用$scope.open的语句。当你在$scope时,Chrome可能已经优化了$scope.open因为你没有使用它。

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

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

0
投票

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

它现在可以正常工作。


0
投票

它为我工作

var app = angular.module("moduleTest",[]);
app.directive("testDirective",function(){
    return {
        restrict: "A",
        scope: true,
        link: function(scope, element){
           //code
           //and $scope is scope
        }
    }   
 });
© www.soinside.com 2019 - 2024. All rights reserved.