我在我的AngularJS(版本1.4)應用程序中有一個工廠。 的代碼是在主app.js
文件:角廠不保留數據
.factory('UserPreferences', function($http, URL, AuthService, store){
var userPreferences = {
"face_shape": '',
"lifestyle": '',
"hair_texture": '',
"email": '',
"postcode": '',
"full_name": '',
"password": ''
};
return {
save_face_shape: function(face_shape){
userPreferences.face_shape = face_shape;
console.log(userPreferences); // -> LINE 307
},
save_lifestyle: function(lifestyle){
userPreferences.lifestyle = lifestyle;
console.log(userPreferences); // -> LINE 311
},
save_hair_texture: function(texture){
userPreferences.hair_texture = texture;
},
get_data: function(){
return userPreferences;
}
}
}). // -> here's another factory
我試圖做的是通過應用不同的步驟來保存用戶prefernces,並且觸發事件後保存在數據庫中的整個用戶。
在頁面的控制,我這樣做,我有以下代碼:
$scope.triggerSecondStep = function(shape){
UserPreferences.save_face_shape(shape);
$scope.step = 2;
}
$scope.triggerThirdStep = function(lifestyle){
UserPreferences.save_lifestyle(lifestyle);
$scope.step = 3;
}
在控制器的觀點,我稱這些功能在一個非常簡單的方法:
<img ng-click="triggerSecondStep('square')" class='hover-opacity' ng-src="LINK_IMAGE" />
由於沒有工作,我添加了一些console.log
打印出中間步驟。我發現的是,上線307打印出console.log
以下輸出,當我打電話triggerSecondStep
:
app.js:307 Object {face_shape: "round", lifestyle: "", hair_texture: "", email: "", postcode: ""…}
app.js:307 Object {face_shape: undefined, lifestyle: "", hair_texture: "", email: "", postcode: ""…}
的console.log
在線路311的輸出如下:
app.js:311 Object {face_shape: undefined, lifestyle: "busy", hair_texture: "", email: "", postcode: ""…}
app.js:311 Object {face_shape: undefined, lifestyle: undefined, hair_texture: "", email: "", postcode: ""…}
所以基本上我不知道爲什麼數據不會從一次調用存儲到另一次調用,以及爲什麼console.log
只輸出一次輸出的兩倍而不是一次。
任何人都可以幫忙嗎?
編輯:
閱讀評論後更新問題(謝謝btw)。
如果我加入一些console.log
在triggerSecondStep
:
$scope.triggerSecondStep = function(shape){
console.log(shape);
UserPreferences.save_face_shape(shape);
console.log(UserPreferences.get_data());
$scope.step = 2;
}
這是輸出(landing_compiled簡直landing.js的編譯版本,與巴貝爾):
square
app.js:308 Object {face_shape: "square", lifestyle: "", hair_texture: "", email: "", postcode: ""…}
landing.compiled.js:72 Object {face_shape: "square", lifestyle: "", hair_texture: "", email: "", postcode: ""…}
landing.compiled.js:70 undefined
app.js:308 Object {face_shape: undefined, lifestyle: "", hair_texture: "", email: "", postcode: ""…}
landing.compiled.js:72 Object {face_shape: undefined, lifestyle: "", hair_texture: "", email: "", postcode: ""…}
如果我添加debugger;
at line 307我看到下面的stackstrace:
一旦我到達最後一步(r.handle
),它只是重新開始,這次沒有參數。
您是否有任何其他對'triggerS的引用econdStep'呢?它看起來好像某個地方你有其他東西沒有參數調用它,並覆蓋你剛剛保存的值。 – Duncan
在行307添加一個'debugger;'語句,並在運行腳本時打開檢查器。您可以檢查堆棧跟蹤以查看誰調用了此方法。其中一個應該是'$ scope.triggerSecondStep' –
你可以記錄數據進入你的控制器功能嗎?例如$ scope.triggerSecondStep = function(shape){console.log(shape) UserPreferences.save_face_shape(shape); $ scope.step = 2; } – user2085143