2014-09-11 75 views
0

我试图让这段代码工作时遇到困难。我正在尝试遵循来自pluralsight的教程,但想要将应用程序文件,控制器文件和服务文件拆分为不同的文件。这样做后,我的代码不再起作用。我错过了什么来使其正常工作?将控制器注入应用程序?

http://plnkr.co/edit/7Mwb1M2e9KvG8zlIDmEx?p=preview

AppFile:

do -> 
    app = angular.module("githubViewer", []) 

控制器的文件:

do -> 
    MainController =($scope, github, $interval, $log, $location, $anchorScroll) -> 
    vm = this 
    vm.username = "angular" 
    vm.sortField = "+language" 
    vm.message = "Github Viewer" 
    vm.countdown = 5 

    onUserComplete =(data) -> 
     vm.user = data 
     github.getRepos.then(onRepos, onError) 
     vm.noError = true 
     return 

    onRepos =(response) -> 
     vm.user.repos = response.data 
     $location.hash("userDetails") 
     $anchorScroll() 

    onError =(reason) -> 
     vm.message = "Could not fetch user" 
     vm.noError = false 
     return 

    vm.search =() -> 
     $log.info("Searching for " + vm.username) 
     github.getUser(vm.username).then(onUserComplete, onError) 
     if(countdownInterval) 
     $interval.cancel(countdownInterval) 
     vm.countdown = null 
     return 

    decrementCountdown =() -> 
     vm.countdown -= 1 
     if(vm.countdown < 1) 
     vm.search() 
     return 

    countdownInterval = null 
    startCountdown =() -> 
     countdownInterval = $interval(decrementCountdown, 1000, vm.countdown) 
     return 

    startCountdown() 

    return 

    app = angular.module("githubViewer") 
    app.controller("MainController", ["$scope", "github", "$interval", 
       "$log", "$location", "$anchorScroll", MainController]) 

服务文件:

do -> 
    github =($http) -> 
    getUser =(username) -> 
     return $http.get("https://api.github.com/users/" + username) 
        .then -> 
        return response.data 

    getRepos =(user) -> 
     return $http.get(vm.user.repos_url) 
        .then -> 
        return response.data 

    return { 
     getUser: getUser, 
     getRepos: getRepos 
    } 

    app = angular.module("githubViewer") 
    app.factory("github", ["$http", github]) 
    return 
+0

我在你指定的plunker链接中运行代码,代码确实运行 - 我得到“无法获取用户”。 – 2014-09-11 03:38:01

+0

以前,他们把所有的角码放在一个文件中,它正在工作,并且能够正确地获取用户。并且在控制台中出现错误,表示响应未定义。 – user4029197 2014-09-11 22:25:30

回答

0

在服务文件中,有A R参考vm.user:

$http.get(vm.user.repos_url) 

但是vm未在脚本中声明或定义。