1

我有自定义指令,例如:

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是可访问的,但内部不是。我究竟做错了什么?

4

1 回答 1

1

那是开发者控制台的产物。内部代码需要引用$location,以便 JavaScript 引擎创建一个闭包

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 引擎创建一个对开发者控制台调试器可见的闭包。

于 2019-01-05T15:18:26.500 回答