2015-10-15 93 views
2

使用AngularJS我試圖做到以下幾點:與工廠和控制器

當用戶訪問「localhost/people/:id」,講述各自的人的有關信息是從MongoDB中取出,並通過角顯示。

我有我的API,它工作得很好,我仔細檢查過。

我正在使用最新的AngularJS(1.4.9)和新的路由器(angular-new-router或ngNewRouter)。

我有一個角模塊:

var personModule = angular.module('app.personDetailed', []); 

工廠:

personModule.factory('personService', ['$http', function($http) { 
    return { 
    get : function(id) { 
     return $http.get('/api/people/' + id); 
    } 
    } 
}]); 

以及控制器:

personModule.controller('PersonDetailedController', ['$routeParams', '$scope', 'personService', PersonDetailedController]); 

function PersonDetailedController($routeParams, $scope, personService) { 

    var id = $routeParams.id; 

    personService.get(id).then(function(res) { 
    $scope.item = res.data; 
    }); 
} 

這一切都應該被顯示在這樣的觀點:

<div data-ng-controller="PersonDetailedController"> 
    <h2>{{ item }}</h2> 
</div> 

(是的,我不打擾試圖解析json呢)。

問題是,我無法同時使用$scope$routeParams。我只能有一個或另一個。如果我同時使用,$scope工作正常,但$routeParams是空的。

這裏的主控制器,以防萬一:

var appModule = angular.module('app', ['app.main', 'app.personDetailed', 'ngNewRouter', 'ngResource']); 

appModule.controller('AppController', ['$router', AppController]); 

function AppController($router) {  
    $router.config([ 
    { path: '/', component: 'main'} 
    { path: '/people/:id', component: 'personDetailed'} 
    ]); 
} 
+0

的DOCO似乎表明您應該使用* 「控制器」 *格式(即沒有'$範圍') – Phil

回答

1

看來新路由器摒棄了$scope並結合控制器實例的模板。

看起來你應該使用this代替

personModule.controller('PersonDetailedController', ['$routeParams', 'personService', PersonDetailedController]); 

function PersonDetailedController($routeParams, personService) { 
    var personDetailed = this, 
     id = $routeParams.id; 

    personService.get(id).then(function(res) { 
     personDetailed.item = res.data; 
    }); 
} 

和你的看法(不使用ng-controller

<h2>{{ personDetailed.item }}</h2> 
+0

謝謝你,完美的工作! – Xonxt