【问题标题】:Angular app is not defined when adding a custom filter outside of function在函数之外添加自定义过滤器时未定义 Angular 应用程序
【发布时间】:2023-03-14 17:16:02
【问题描述】:

尝试遵循一些示例,但我得到 app is not defined

app.js

(function () {
   "use strict";
   var app = angular.module("deviceManagement",['angularUtils.directives.dirPagination']);
}());

所以我希望能够使用或附加到“应用程序”

我有一个控制器 js 文件

(function () {
   "use strict";
angular
    .module("deviceManagement")
    .controller("DeviceListCtrl",
    ProductListCtrl);

function ProductListCtrl($http, $scope) {
    var vm = this;

    vm.devices = [];

    deviceList();


    function deviceList() {

      //..........
    }

  }
} ());

然后在上面的代码下我这样做

app.filter('deviceStatus', function () {

    var deviceStatusLookup = {
        1: "New Device",
        2: "Activated",
        3: "Unactivated"
    };

    return function (statusId) {
        var output = deviceStatusLookup[statusId];
        return output;
    }
});

页面控制台错误

deviceListCtrl.js:73 Uncaught ReferenceError: app is not defined

【问题讨论】:

  • 我认为您应该在 deviceListCtrl.js 中使用 app.controller 代替 angular.controller

标签: javascript angularjs angularjs-directive angularjs-scope


【解决方案1】:

检查您是否包含了 app.js 文件。

另外,我会更改以下内容:

app.filter('deviceStatus', function () {

到这里:

angular
    .module("deviceManagement")
    .filter('deviceStatus', function () {

最好不要使用 var app 而只引用模块,例如angular.module(“设备管理”)。看到这个answer

【讨论】:

  • 是的@ScottL,这绝对是最好的方法。
  • 谢谢,这对我来说很有意义。
【解决方案2】:

在你的情况下,问题在于这里:

(function () {
   "use strict";
   var app = angular.module("deviceManagement",['angularUtils.directives.dirPagination']);
}());

您在 lambda 函数中有 app,它就存在于其中。

要使其正常工作,您应该:

(function (window) {
   "use strict";
   var app = angular.module("deviceManagement",['angularUtils.directives.dirPagination']);
   window.app = app || {};
}(window));

因此,我们在 lambda 中注入 window 元素,以便您可以全局定义 app (window.app = app || {})。

注意:考虑到 window.app 方法不是最好的。

angular.module("deviceManagement") 语法可能是最好的方法,可以让您的代码更加模块化。

【讨论】:

  • 1.你不是说IIFE吗? (不是 lambda) 2. 有什么更好的方法?
  • 感谢@CodingAway 我不得不承认我不知道(function(){ ... })() 的模式名称是IIFE。语法function() 用于匿名函数,所以我称之为lambda
  • @ScottL 建议的最佳方法是 angular.module("deviceManagement") 一种,但它没有解释为什么您会收到 app is not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2021-06-07
  • 2021-08-23
  • 2021-04-06
  • 1970-01-01
  • 2016-12-26
相关资源
最近更新 更多