javascript - 导入 Angular JSON 对象

标签 javascript angularjs json

我有一个带有以下对象的 Angular 1.x Controller :

notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                     { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                     { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                     { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                     { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                    ],

它用于在单个页面上填充一些列表。但是,我现在的情况是需要在其他页面上重用它。我可以将其复制到适当的页面,但我宁愿重构它,以便两个 Controller 都从同一个列表工作,以获得更好的可维护性。我一直试图在“MainApp”模块上将其声明为常量、工厂和/或指令,但没有成功。我错过了什么?

最佳答案

使用工厂来解决这个问题。更改页面时,数据可以保留在工厂和服务中。

angular.module('App', [...])

.factory('NotificationFactory', function () {
    var notificationTypes: [ { NotificationType: '*', NotificationTitle: 'All notifications' },
                 { NotificationType: '0', NotificationLabel: 'System Alert', NotificationTitle: 'System alerts' },
                 { NotificationType: '1', NotificationLabel: 'Pending Task', NotificationTitle: 'Pending tasks' },
                 { NotificationType: '2', NotificationLabel: 'Update', NotificationTitle: 'Updates' },
                 { NotificationType: '3', NotificationLabel: 'Missed Message', NotificationTitle: 'Missed messages' }
                ];

    return notificationTypes;
})

关于javascript - 导入 Angular JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720473/

相关文章:

javascript - MutationObserver 回调何时触发?

javascript - 错误处理 promise 在 mongoDB 中保存唯一数据(ValidationError)

javascript - 为什么这个分组 Angular 过滤器会导致摘要循环?

java - Struts2 REST 插件 : Passing array in JSON

ios - SwiftUI-从JSON文件显示数组

jquery - 直接将json字符串写入script标签中

javascript - jQuery 添加一个类但不会删除一个

javascript - 将动态网页 (Kibana) 的一部分嵌入到我自己的网站中

javascript - 如何在表格元素中填充数据?

angularjs - (注入(inject)函数的)参数上的下划线是什么意思?