2015-10-13 26 views
0

我有一個名爲MapController MapController.js正確的方式來更新像工廠獨身AngularJS

var self = this; 
self.factory = MapStateFactory; 
self.origin = self.factory.originCity; 
self.destination = self.factory.destinationCity; 

//The wrong way 
//Updating self.origin will shadow the value and will no longer point to the factory 
self.changeOrigin = function() { 
    self.origin = { 
     name: 'New Origin' 
    }; 
}; 

//However, this is still incorrect. 
//It popluates the change in the factory but if I output self.destination on the page, it hasnt updated 
self.changeDestination = function() { 
    //This also doesn't update both locations if I use 
    //MapstateFactory.destinationCity = '' 
    self.factory.destination = { 
     name: 'New Destination' 
    }; 
}; 

下面的控制器如果你只是認爲我廠是一家集標準廠房,沒有有趣的業務,如何正確使用這些函數更新工廠(如果有任何意義的話,這些函數附加到按鈕上)。

這是我struggline與目前的問題。 我所遇到的唯一的解決辦法是做一個手錶MapStateFactory.originCity的,這似乎非常凌亂的價值...

我可以做這樣的事情

self.changeDestination = function() { 
    self.destination = { 
     name: 'New Destination' 
    }; 
    self.factory.destinationCity = { 
     name: 'New Destination' 
    }; 
}; 

肯定這是不好的做法?

回答

1

不要重新分配整個對象或者你打破引用考慮下面的簡單例子原來的對象

var a ={name:'foo'}, b=a; 

可以更改name財產做:

a.name = 'bar' 
// or 
b.name = 'bar' 

a.nameb.name的值將是相同的。

但是,如果你這樣做更新a

a = {name: 'bar'} 

您分配一個完全不同的對象a,破了參考原始對象。現在ab沒有引用相同的對象,以便於a特性所做的更改不會影響b性能

在你的情況,你需要改變:

self.factory.destination = { 
    name: 'New Destination' 
}; 

要:

self.factory.destination.name = 'New Destination' ; 

或與多個屬性比較大的改變,你可以使用方法如angular.extend()

angular.extend(self.factory.destination, {name: 'New Destination', cost:500 }); 
+0

爲此乾杯。這真的是我需要有人指出的其中一件事,因爲我不知道發生了什麼事情!多謝! – Aleski