相同的控制器并解决不同的状态

时间:2017-01-26 14:41:51

标签: javascript angularjs

我有以下配置。有一种方法可以使它更干净,没有重复的代码吗?

谢谢!

.state('info', {
    url: '/info/:id',
    templateUrl : 'templates/pages/info.html',
    controller : 'singlePage',
    resolve: {
       pageData: function(getData, $stateParams) {
            var params = $stateParams;
            params.type = this.self.name;
            return getData.getPageData(params.type, params)
       }
    }
})
.state('news', {
    url: '/news/:id',
    templateUrl : 'templates/pages/news.html',
    controller : 'singlePage',
    resolve: {
       pageData: function(getData, $stateParams) {
            var params = $stateParams;
            params.type = this.self.name;
            return getData.getPageData(params.type, params)
       }
    }
})
.state('event', {
    url: '/event/:id',
    templateUrl : 'templates/pages/event.html',
    controller : 'singlePage',
    resolve: {
       pageData: function(getData, $stateParams) {
            var params = $stateParams;
            params.type = this.self.name;
            return getData.getPageData(params.type, params)
       }
    }
})

1 个答案:

答案 0 :(得分:2)

function createState(name) {
    return {
        url: '/' + name + '/:id',
        templateUrl : 'templates/pages/' + name +'.html',
        controller : 'singlePage',
        resolve: {
           pageData: function(getData, $stateParams) {
                var params = $stateParams;
                params.type = this.self.name;
                return getData.getPageData(params.type, params)
           }
        }
    }
}

....

.state('info', createState('info'))
.state('news', createState('news'))
.state('event', createState('event'))