我想知道什么最好的方法来解决在angularjs模型和承诺之间有很多关系。请允许我举个例子,如果能有更好的实施方法,我会非常乐意提供您的反馈意见。Angularjs处理承诺和模型
一个Surah
有很多Ayahs
我Surah
型号:
angular.module('qurancomApp')
.service 'Surah', (Restangular, userOptions, Ayah) ->
class Surah
constructor: (obj) ->
for key of obj
@[key] = obj[key]
getAyahs: (from, to) ->
self = @
@ayahs = Ayah.all
surah_id: @id, from: from, to: to
.then (ayahs) ->
self.ayahs = ayahs
@new: (id)->
return Restangular.one('surahs', id).get().then (data)->
return new Surah(data)
@all: ->
return Restangular.all("surahs").getList()
我Ayah
型号:
angular.module('qurancomApp')
.service 'Ayah', (Restangular, userOptions) ->
# AngularJS will instantiate a singleton by calling "new" on this function
class Ayah
constructor: (obj)->
for key of obj
@[key] = obj[key]
@all: (hash) ->
Restangular.one('surahs', hash.surah_id).getList 'ayat',
content: userOptions.content, quran: userOptions.quran, audio: userOptions.audio
.then (data)->
ayahs = data.map (ayah) ->
# The ayah object is returned from Restangular and given all the properties that restangular gives it. For example, you can call
# ayah.save() or ayah.remove() which will make API calls accordingly. This is power and will be perserved when creating the Ayah object
return new Ayah(ayah)
return ayahs
和相应的控制器:
angular.module('qurancomApp')
.controller 'AyahsCtrl', ($scope, $routeParams, Surah) ->
rangeArray = $routeParams.range.split("-")
Surah.new($routeParams.id).then (surah) ->
$scope.currentSurah = surah
console.log $scope.currentSurah.getAyahs(rangeArray[0], rangeArray[1])
真的,问题是:在控制器中,我称之为功能Surah.new()
,然后向前走并取入该Surah
从后端,然后要创建它相关的Ayahs
,这是我注入Ayah
模型到Surah
模型和有在Surah
模型中正在消化的Ayah
模型上的承诺,在Surah.new()
函数的整体承诺内。
这是一个正确的方法来做到这一点?能有更好的方法吗?