i have a problem with an http.get.
Index.html
<div ng-repeat="element in elements">
<p>{{element.elementText}}</p>
</div>
app.js
I have two controllers. First one initialize $scope.elements with a json and works:
$http.get('someUrl')
.success(function (response) {
$scope.elements = response;
})
Seconde one update $scope.elements with a another json when a scope function is called by ng-click:
$scope.updateScope = function () {
$http.get('someOtherUrl')
.then(function (response) {
$scope.elements = response.data;
});
But when i call updateScope nothing appens. I try use .success but nothing. I try using $scope.$apply after assign response to $scope.elements but it generates an error (Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.11/$rootScope/inprog?p0=%24digest).
UPDATE - If I reload page ng-repeat on scope element works correctly. So $scope.elements contains right values but ng-repeat doesn't update itself. Sorry for my english...
Could you help me please?
答案 0 :(得分:1)
.then(function (response) {
and .success(function (response) {
gets different objects in their callbacks. In the first case you get the response's data directly, in second it will be wrapped in an object (that has also other properties - like status
, config
, statusText
, and so on).
If you use .then
your response's body will be in sth.data
, not in sth
. So in your case:
$scope.updateScope = function () {
$http.get('someOtherUrl').then(function (response) {
$scope.elements = response.data;
});
答案 1 :(得分:0)
You can use angular.merge
angular.merge(object1, object2)
答案 2 :(得分:0)
To share data you want to use a service, not root scope. Consider an example like this:
<div ng-app="app">
<div ng-controller="controller1 as vm">
<input type="text" ng-model="vm.dataService.data" />{{vm.dataService.data}}</div>
<div ng-controller="controller2 as vm">
<input type="text" ng-model="vm.dataService.data" />{{vm.dataService.data}}</div>
</div>
var app = angular.module('app', []);
app.factory('DataService', function () {
var data;
return {
data: 'Hello, World!'
};
});
app.controller('controller1', function (DataService) {
var vm = this;
vm.dataService = DataService;
});
app.controller('controller2', function (DataService) {
var vm = this;
vm.dataService = DataService;
});
Here is a jsFiddle that runs that code.
答案 3 :(得分:-1)
you can try following code.(you need to include $timeout)
$scope.updateScope = function () {
$http.get('someOtherUrl')
.then(function (response) {
$scope.elements = response;
$timeout(function(){
$scope.$apply();
});
});