将控制器注入App?

时间:2014-09-11 03:04:39

标签: angularjs coffeescript

我在尝试使用这段代码时遇到了困难。我试图遵循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

1 个答案:

答案 0 :(得分:0)

在服务文件中,有对vm.user的引用:

$http.get(vm.user.repos_url)

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