我有以下指令。当我触发open函数并进入调试器时,我在控制台中收到一条错误消息,显示为Uncaught ReferenceError: $scope is not defined(…)。
当$scope未定义时,如何调用$scope.open?
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>如果我在open函数之前插入console.log($scope),然后在该函数中的debugger之前再次插入,我会得到以下结果。左边是在调用open之前,右边是在调用open之后。

发布于 2016-02-09 03:07:29
您在指令定义中注入了$http和modal (正如您所做的那样),不需要在控制器函数中,只需执行以下操作:
controller: function($scope) {
$scope.prev = $scope.index - 1;
$scope.open = function() {
debugger;
};
}发布于 2016-02-09 03:13:17
尝试在$scope.open中添加使用$scope的语句。当你在$scope.open中时,Chrome可能已经优化了$scope,因为你不使用它。
$scope.open = function() {
console.log($scope);
debugger; //now you should see $scope.
};发布于 2016-02-09 03:07:39
这应该是可行的:
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;
};
}
}
}]);https://stackoverflow.com/questions/35277295
复制相似问题