Reputation: 3104
Without injecting services how to pass data from one view's controller to another view. I refered data,params, resolve, parent-child concepts but I am not able to figured it out.
Here is the example:
Routing:
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html",
controller: "firstCtrl"
})
.state('route2', {
url: "/route2",
templateUrl: "route2.html",
controller: "secondCtrl"
})
Views:
route1.html
view 1 : {{firstCtrlValue}}
route2.html
View 2: <input type="text" ng-model="firstCtrlValue"/> <!-- Of course, It won't work -->
<a ui-sref="route1">go to route 1</a>
<a ui-sref="route2">go to route 2</a>
Controllers:
.controller('firstCtrl', function($scope) {
$scope.firstCtrlValue = "I am from first";
})
.controller('secondCtrl', function($scope) {
$scope.secondCtrlValue = "Hey I'm from 2nd Ctrl";
});
What I want: If i change the model value from route2 it must affect route1.
Here is the link
Upvotes: 0
Views: 623
Reputation: 18875
I see two ways of getting this done:
Use localCache
or sessionCache
in your browser for saving/retrieving the data that both views need. There is a very nice angular plugin for doing this here. Every controller updates/retrieves the data through the cache.
Create a custom service
in your app that has APIs for saving and retrieving the data. Whenever a new value is stored in the service, then use $rootScope.$broadcast()
to notify the other controller of the changes so it can fetch the new value.
If neither of these two approaches is what you want, you can try to put a resolve {}
block in your state config like the following:
$stateProvider
.state('route1', {
url: "/route1",
templateUrl: "route1.html",
controller: "firstCtrl",
resolve: {
DataService: 'DataService',
dataObj: function(DataService) {
return DataService.getDataObj(); // a promise (e.g. return $http.get(url))
}
}
})
Then in your controller firstCtrl
, you need to inject the dataObj
:
function firstCtrl($scope, dataObj) {
//TODO: use dataObj as a value or object however you want
}
In your DataService
, you need to make sure the function getDataObj()
returns a promise though, example:
function getDataObj() {
var deferred = $q.defer();
deferred.solve({key: "value..."});
return deferred.promise; //can also be return $http.get(url) of that sort
}
Upvotes: 1