" TypeError:无法读取属性' name'未定义" Angular页面刷新后出错

时间:2014-04-28 04:36:27

标签: ruby-on-rails angularjs angularjs-scope

很抱歉,如果这是一个简单的问题,我是角色的新手,并尝试将其集成为基本的rails博客应用程序的前端。我有点困在一个我认为与角度承诺有关的问题,但不确定。页面刷新后,我在控制台中收到以下错误:

TypeError: Cannot read property 'name' of undefined
at Object.$scope.prepArticleData 

我有一个articleData服务,当我将url指向ArticleIndex页面时,它会加载所有表数据,并在Index页面上单击链接时加载单个文章。但是,当我在浏览器中刷新单个文章页面时,currentArticle对象数据将丢失,而数据将替换为具有角度花括号的视图中的数据。我用谷歌搜索了一下,但似乎无法找到它破裂的原因。任何指导都非常感谢!

文章服务

angular.module('app').factory('articleData', ['$http', ($http) ->

articleData =
data:
  articles: [{name: 'Loading', content: ''}]
isLoaded: false

articleData.loadArticles = (deferred) ->
if !articleData.isLoaded
  $http.get('./articles.json').success( (data) ->
    articleData.data.articles = data
    articleData.isLoaded = true
    console.log('Articles loaded successfully.')
    if deferred
      deferred.resolve()
  ).error( ->
    console.error('Failed to load articles.')
    if deferred
      deferred.reject('Failed to load articles.')
  )
 else if deferred
    deferred.resolve()

articleData.createArticle = (newArticle) ->
# Client-side data validation
if newArticle.newArticleName == '' or newArticle.newArticleContent == ''
  alert('Neither the Title nor the Body are allowed to be left blank.')
  return false

# Create data object to POST
data =
  new_article:
    name: newArticle.newArticleName
    content: newArticle.newArticleContent

# Do POST request to /articles.json
$http.post('./articles.json', data).success( (data) ->

  # Add new article to array of articles

  articleData.data.articles.push(data)
  console.log('Successfully created article.')

).error( ->
  console.error('Failed to create new article.')
)

return true

return articleData

])

物品管理员

@ArticleCtrl = ($scope, $routeParams, $location, articleData) ->

$scope.data =
articleData: articleData.data
currentArticle:
  name: 'Loading...'
  content: ''

$scope.data.articleId = $routeParams.articleId

articleData.loadArticles()

$scope.prepArticleData = ->
article = _.findWhere(articleData.data.articles, { id: parseInt($scope.data.articleId) })
$scope.data.currentArticle.name = article.name
$scope.data.currentArticle.content = article.content


$scope.prepArticleData()

@ArticleCtrl.$inject = ['$scope', '$routeParams', '$location', 'articleData']

此路线在routeProvider中设置,以将当前选定的文章加载到mainArticle视图中:

 when('/article/:articleId', { templateUrl: '../assets/mainArticle.html', controller: 'ArticleCtrl' }).

主要文章观点:

<h2 class="text-left">{{ data.currentArticle.name }}</h2>
<div class="">
<p>{{ data.currentArticle.content }}</p>
</div>

<div class="row">
<button class="btn btn-default" ng-click="editPost()">Edit</button>
</div>

似乎必须在刷新页面时在ArticleCtrl中调用prepArticleData函数,并且相对的articleId再次从url传递,但我不知道该怎么做。提前谢谢!

1 个答案:

答案 0 :(得分:1)

看来,在您致电articleData.loadArticles()之前,异步通话$scope.prepArticleData()未完成

这会导致findWhere不返回任何内容而下一行失败

您应该在承诺成功回调上致电$scope.prepArticleData()