2015-01-12 94 views
1

我正在嘗試包含在我的Angular應用程序中有用的其他「模型」對象。假設我有兩個單獨的javascript文件,如下所示。我想爲我的老師原型添加一個「createStudent」函數,並讓它調用學生構造函數方法。 teacher.js如何正確引用student.js?這裏注入的方法是什麼?在Angular中注入模塊值

僅供參考,我知道在Angular中包含豐富對象模型的方法很多。例如,我現在不想採用Restangular的路線。我現在想保持這個非常簡單,並希望增加我對角度模塊的理解。

謝謝!

---------- ----------- teacher.js

(function() { 
 

 
    var teacherConstructor = function() { 
 

 
     var teacher = { 
 
      student: [] 
 
     }; 
 
     
 
     return teacher; 
 

 
    }; 
 

 

 
    var module = angular.module("MyApp.models"); 
 
    module.value("teacber", teacberConstructor); 
 
}());

--------- - student.js

(function() { 
 

 
    var studentConstructor = function(theTeacher) { 
 

 
     var student = { 
 
      myTeacher: theTeacher 
 
     }; 
 
     
 
     return student; 
 

 
    }; 
 

 

 
    var module = angular.module("MyApp.models"); 
 
    module.value("student", studentConstructor); 
 
}());

回答

2

一種可能的解決方法 - 使用factory

(function() { 
    var module = angular.module("MyApp.models"); 

    module.factory("teacher", ["student", function(Student) { 
     var teacherConstructor = function() { 
      ... 
      var student = new Student(this); 
      ... 
     }; 

     return teacherConstructor; 
    }]); 
})(); 

反正老師「下課」的定義必須角的定義函數中完成,它能夠引用的學生。

然而這引入了不必要的結束。我建議下降外功能,有利於角的土辦法:

angular.module("MyApp.models").factory("Teacher", ["student", function(Student) { 
    var Teacher = function() { 
     ... 
     var student = new Student(this); 
     ... 
    }; 

    return Teacher; 
}]); 

一點題外話,這是習慣的「類」啓動資本。即StudentTeacher。而構造函數也可以有這個類的名字,因此在上面的代碼中有teacherConstructorTeacher

+0

謝謝!這是照明。後續問題: 我假設這些.factory()調用中只有一個可以注入另一個,否則我會產生循環依賴。所以我必須選擇老師是否創造新的學生,或者學生是否創造它的老師。是對的嗎? 還有一條評論:我一直試圖避免使用'新'關鍵字作爲每Crockford的書「Javascript:好部件」,因爲使用構造函數而不是新教師()提供了很多優勢,比如在一個對象上執行私有和公共函數的能力。 –

+0

嗨!關於循環:是的,你是對的 - 但這會成爲任何語言的問題。您仍然可以通過'new'操作員擁有私人成員 - 我當然可能會遺漏一些細節。但最有成效的(IMO)是選擇一個適合你的風格,所以確信,構造函數沒有問題。 (有些人甚至會主張完全放棄OO邏輯,並用Javascript一路發揮功能:) –

+0

Angular似乎有助於通過提供服務來實現函數式編程,而據我所知,這些服務是直接單身人士。我想簡單地將我的對象圖變成一堆有效的靜態函數,但不能讓自己做到這一點。 –

相關問題