I'm using AngularJS 1.5, ui-router, and angular-resource and I am developing a component-based application. I have one parent state, which is used for getting and updating data, this data is bound to multiple child states via a parent state resolver.
When I change the data manually in the parent component controller (e.g. vm.town.x = 666), everything works fine and the change is visible in the child state components. However, when I change data in the parent component controller from the response of the rest service (using angular-resource), the data change is visible only in the parent state component.
state definition:
.state('town', {
url: '/my-towns/:townId/',
component: 'town',
bindings: {
town: 'townData'
},
resolve: {
townData: function(Town, $stateParams) {
return Town.get({
townId: $stateParams.townId
});
}
}
})
.state('town.detail', {
url: 'detail',
component: 'townDetail',
bindings: {
town: 'townData'
}
})
parent (town) component controller definition:
function TownCmpController(TownServices,Town,BuildingUpgradeRest) {
var vm = this;
this.upgradeBuilding = function(data) {
vm.town = BuildingUpgradeRest.update({townId: vm.town.TownId,buildingId: data.building.BuildingId});
}
rest service definition:
.factory('BuildingUpgradeRest',function($resource){
return $resource('api/public/v1/myaccount/towns/:townId/buildings/:buildingId/upgrade', {townId:'@townId', buildingId: '@buildingId'}, {
'update': {
method: 'PUT'
}
});
})
'town' object binding is same in both components
bindings: {
town: '<'
}
Both services return the same object type and both work.
townbound to their inputs. When you change the value ofvm.townyou are overwriting the reference on the parent controller. But the child controller isn't bound to the parent controller; it's bound to the resolved value. If you look at the DOM you will see<town-detail town="::$resolve.town"></town-detail>townIdstate param so that the town is re-fetched cleanly. If the townId hasn't changed, you can use the{ reload: 'town' }transition option to force the town resolve to re-fetch.vm.town.x = 666in parent component controller and everything works (the changes are visible in child states components). But only change vm.town by calling the serviceBuildingUpgradeRest.update()doesn't work. If I understand your suggestion, it means I need to call my rest services 2x for every change of town object (first call for change, second call in state resolve)?vm.town.xyou are changing a property on an object. Because the same object is bound in both controllers, the change is reflected. However, changingvm.townactually changes the vm's reference to a different object. In the other controller, the reference to the original object is still the old one.