未调用内部JS Angular Controller

Internal JS Angular Controller not getting called

本文关键字:Angular Controller JS 内部 调用      更新时间:2024-04-11

我已经在HTML的脚本标记中编写了一个控制器。当我运行代码时,代码会一直执行到依赖项注入,但回调函数不会执行。

当类似的代码在我工作过的其他应用程序上成功运行时,我无法弄清楚这是怎么回事。

此外,如果我显式调用回调函数,那么注入的依赖项就不会被识别。

<script type="text/javascript">
    angular.module('DesignPortal.layout', [])
        .controller('NgLayoutController', NgLayoutController);
    NgLayoutController.$inject = ['$scope'];
    function NgLayoutController($scope) {
        var loggedUserId = dpConfig.userInfo.id;
    }
</script>

如果显式调用函数,则不会识别上面注入的作用域。

它正在处理我的plunk。

<script type="text/javascript">
    angular.module('DesignPortal.layout', [])
        .controller('NgLayoutController', NgLayoutController);
    NgLayoutController.$inject = ['$scope'];
    function NgLayoutController($scope) {
      alert("Its working!");
        var loggedUserId = dpConfig.userInfo.id;
    }
</script>

发生这种情况的原因有很多,例如删除模块的index.html脚本,但留下模块依赖项,甚至拼错了模块依赖项。

您需要做的第一件事是确保所有模块依赖项拼写正确,然后确保加载了所有文件。

控制台中有错误吗?可能是在加载angular之前加载了脚本。尝试将代码封装在函数中,并放置一些断点/debugs/console.log来测试代码在哪个点执行。

(function(){
  "use strict";
  angular.module('DesignPortal.layout', [])
      .controller('NgLayoutController', NgLayoutController);
  NgLayoutController.$inject = ['$scope'];
  function NgLayoutController($scope) {
      var loggedUserId = dpConfig.userInfo.id;
  }
})();

试试这个。我没有尝试过,但应该会成功的。

<script type="text/javascript">
    angular.module('DesignPortal.layout', [])
        .controller('NgLayoutController',['$scope', function($scope) {
            function NgLayoutController() {
                var loggedUserId = dpConfig.userInfo.id;
            }
        }]);    
</script>