我有如下自定义指令:
angular.module('app.directive').directive('myProductSwitcherDropdown',myProductSwitcherDropdown);
myProductSwitcherDropdown.$inject = ['$compile'];
function myProductSwitcherDropdown() {
return {
restrict: 'E',
transclude: 'true',
scope: {
domainobject:"=",
ctrlFn:"&"
},
templateUrl: "src/directive/templates/my-product-switcher-dropdown.html",
controller: ['$scope', 'UtilService', function($scope,UtilService) {
debugger;
var self = this;
$scope.instance =self;
self.dropDownChanged = function(item) {
debugger;
$scope.ctrlFn();
};
}],
controllerAs: 'myProductSwitcherDrpdwnCtrl'
}
}
我正在这样调用指令:
<div class='notification-tray'></div>
<div class="left-menu pull-left">
<my-product-switcher-dropdown domainobject="domainobject" ctrl-fn="ctrlFn()">
</my-product-switcher-dropdown>
</div>
但是在我的控制器中,当我在ctrlFn()
内尝试使用say $location or $window
时,它的名称为 undefined 。
我也注射了这些东西。
angular.module('workspaces.domain').controller('DomainController',DomainController);
DomainController.$inject = ['$scope', '$rootScope', '$location'];
function DomainController ($scope, $rootScope, $location) {
var self = this;
....
....
//$location is accessible here though
$scope.ctrlFn = function () {
//Undefined here
debugger;
};
在ctrlFn()
$location
可以访问之前,但在内部却无法访问。 我在做什么错了?
答案 0 :(得分:1)
这是开发者控制台的构件。内部代码需要引用$location
,以便JavaScript引擎创建closure:
angular.module('workspaces.domain').controller('DomainController',DomainController);
DomainController.$inject = ['$scope', '$rootScope', '$location'];
function DomainController ($scope, $rootScope, $location) {
var self = this;
....
....
//$location is accessible here though
$scope.ctrlFn = function () {
//ADD reference to $location
$location;
//OR
console.log($location);
//Will also be defined here
debugger;
};
这两种方法都强制JavaScript引擎创建closure,这对于开发者控制台调试器是可见的。