【问题标题】:$location is not working in AngularJS Custom Directive$location 在 AngularJS 自定义指令中不起作用
【发布时间】:2019-01-04 09:57:32
【问题描述】:

我有自定义指令,例如:

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

【问题讨论】:

  • 如果$location 被正确注入,它没有理由不能在内部函数中作为closure 使用。我认为您对代码进行了如此多的疯狂编辑,以至于您自己感到困惑。放慢速度,采取更有条理的方法来调试代码。

标签: javascript angularjs angularjs-directive


【解决方案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,这将对开发者控制台调试器可见。

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 2018-02-06
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多