ng-show="my.message" is set to true in http success but it doesn't update the view.
Here is my code:
Controller Js:
lgControllers.controller('FormCtrl', function($scope, $http) {
$scope.my = {
message: false
};
$scope.submitForm = function() {
$http({
url: "../saket/ajax.php",
data: "email_id=" + $scope.form.emailaddress + "&category_id=" + cat_num + "&action=subscribe",
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data) {
$scope.my = {
message: true
};
console.log(data); // http is success
console.log($scope.my.message); // gives true
}).error(function(err) {
"ERR", console.log(err)
})
};
});
Index.html:
<div ng-controller="FormCtrl">
<div ng-show="my.message">It worked!</div>
</div>
my.message gives true in console but the div remains hidden in the view.
I can't figure out where the problem is.
Can it be that you are overwriting the message property, and angularjs is loosing the reference?
$scope.my = {
message: true
;
try just :
$scope.my.message = true;
Related
In my ui-bootstrap modal I have 3 modal-body div's.
<div class="modal-body" ng-show="$ctrl.selected.item == 'registration'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'thanks'">...</div>
<div class="modal-body" ng-show="$ctrl.selected.item == 'error'">...</div>
By changing $ctrl.selected.item I change HTML inside my modal window. Now I need to change this variable(property of object indeed) inside a registerService which is injected do registerwindow' controller.
app.service('registerService', ['$http', 'localStorageService', function ($http, localStorageService) {
this.registerUser = function (registerInfo) {
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
$ctrl.selected.item = $ctrl.items[1];
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
$ctrl.selected.item = $ctrl.items[2];
})
};
}]);
This approach with $ctrl.selected.item = $ctrl.items[1]; doesn't work obviously.. How can I do this? I have no clue I need to do this asynchronously.
You could probably use Angular's $q service to handle this. The service's method would look like this:
this.registerUser = function (registerInfo) {
var deferred = $q.defer();
$http({
url: 'http://localhost:3000/v1/sign_up',
headers: {
'Content-Type' : 'application/json'
},
method: 'POST',
data: {
email: registerInfo.email,
nick: registerInfo.nick,
password: registerInfo.password,
password_confirmation: registerInfo.password_confirmation
}
})
.then(function successCall(response) {
console.log('user added'); // delete it
//$ctrl.selected.item = $ctrl.items[1];
deferred.resolve(); //Resolve the promise - success
}, function errorCall(respone) {
console.log('error callback register ');
console.log(respone.data);
//$ctrl.selected.item = $ctrl.items[2];
deferred.reject(); //Reject the promise - failure
});
return deferred.promise;
};
Remember to inject $q into your service!
Within your controller, you'd call your service method like so, then adjust the scope variable within the .then and .catch:
registerService.registerUser(registerInfo)
.then(function() {
$scope.selected.item = $scope.items[1];
//Not sure what your controller looks like, you may be using controllerAs, so this will be a bit different
})
.catch(function() {
$scope.selected.item = $scope.items[2];
});
i want to get just my service in the variable from my controller but it give me an $$state object
this is my controller
$scope.myDataSMS = ServiceSms.async().then(function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
});
console.log($scope.myDataSMS);
and my service
routeAppControllers.factory('ServiceSms', function($http,Token) {
var key = Token.CreateToken()
var myService = {
async: function() {
var data = 'token=' + encodeURIComponent(key);
var promise = $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data) {
// The then function here is an opportunity to modify the response
// console.log(data.data);
// The return value gets picked up by the then in the controller.
return data.data;
})
// Return the promise to the controller
return promise;
}
};
return myService;
});
i think that the problems is with the promise but there i m little bit stuck
if someone can help me please
thanks in advance
this would be a better way to write your promise:
CONTROLLER:
.controller('nameofcontroller', ['$scope', 'ServiceSms', function($scope, ServiceSms) {
$scope.myDataSMS = ServiceSms.async()
.then(
function(data){
$scope.myDataSMS1 = data;
console.log($scope.myDataSMS1);
return $scope.myDataSMS1;
},
function(err){
console.log('err: ' + err);
});
}]);
SERVICE:
routeAppControllers.factory('ServiceSms', function($http,Token) {
return {
async: function() {
var data = 'token=' + encodeURIComponent(key);
return $http({
method: 'POST',
url: 'PhpFunction/getsms.php',
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}
});
My app goes into infinite loop while firing $http get method inside a function
In my controller I am using POST and getting data from API after authorization and displaying it.
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope, $http) {
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
})
.then(function(response) {
$scope.hotels = response.data;
});
$scope.imagePath = function(id) {
console.info(id);
if (id) {
$http({
method: 'GET',
url: 'url=' + id
})
.then(function(response) {
var imgdata = response.data;
console.info(imgdata);
var imgdata1 = imgdata.data.image_name;
return "url" + imgdata1;
});
}
};
});
In my img ng-src I have to call data from another API from the key exterior_image which I am passing in my function but it goes into an infinite loop. Also I know I have to use angular forEach in imgdata1.
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='hotel'></select>
<h1>{{hotel.hotel_name}}</h1>
<p>{{hotel.hotel_description}}</p>
<img ng-src="{{imagePath(hotel.exterior_image)}}">
</div>
Try this in your Controller:
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_name: "Default Value Here",
hotel_description: "Default Value Here",
exterior_image: "Default id here",
image_url: "Default url here"
};
$http({
url: 'url',
method: "POST",
data: 'postData',
headers: {
'Authorization': 'value'
}
}).then(function (response) {
$scope.hotels = response.data;
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: 'url=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "url" + imgdata1;
});
};
});
and this:
<div ng-controller='ctrl1'>
<select ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img ng-src="{{current_Hotel.image_url}}">
</div>
i have the following code for save operation:
here is my angular service: this already returns the promise
factory('customersaveService', function ($http, $q) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
var deffered = $q.defer();
$http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
.success(function (d) {
deffered.resolve(d);
})
.error(function (e) {
deffered.reject(e);
});
}
return factoryObject;
});
in here the promise is returned. therefore it shoudl not throw the error
"TypeError: Cannot read property 'then' of undefined"
the error comes from the controller's code:
$scope.SaveCustomer = function (data)
{
if ($scope.ButtonText == 'Save')
{
$scope.message = "";
$scope.submitted = true;
$scope.User = data;
console.log($scope.User);
customersaveService.SaveNewUserSrv($scope.User).then(function (d) { <=== error line
console.log('before success part');
if (d == 'success')
{
console.log('im in success part');
clearform();
}
},
function (e) {
});
}
}
why this throws the error when the promise was returned?
1.Create service like below :
2.No need of $q service.
factory('customersaveService', function ($http) {
var factoryObject = {};
factoryObject.SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: JSON.stringify({ 'cust': data }),
})
}
return factoryObject;
});
factory('customersaveService', function ($http) {
var SaveNewUserSrv = function(data) {
return $http({
url: 'CustomerTest1/SaveNewUser',
method: 'POST',
headers: { 'content-type': 'application/json' },
data: { 'cust': data }
});
};
return {
SaveNewUserSrv: SaveNewUserSrv
};
});
And in the controller, sure you inject the service customersaveService
I have what would seem to be a simple problem with AngularJS - apologies if so. I'm new and have searched all over and can't quite find an answer to what I want to do.
Basically I have a $http request that is getting a list of 'Cards' from a server which I'm then using ng-repeat to build in the HTML. I then want to populate those Cards with a number of 'Metrics' - also retrieved from the server. I have a controller for the 'Cards' (parents) and a separate controller for the 'Metrics' (children).
My issue is that I can't work out how to reference the ID of the parent 'Card' when making the child $http request.
Below is the HTML & JS that I am using - any help would be appriciated:
HTML:
<div class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
<div ng-repeat="Card in Dashboard.DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric">
<div ng-repeat="Metric in Metric.DashboardMetrics">
{{Metric.MetricDisplayName}}
</div>
</div>
</div>
</div>
JS:
(function () {
var app = angular.module('OtterDashboard', [ ]);
app.controller('DahsboardCardController', [ '$http', function($http) {
//Declare a varaible for the data
var DashboardCards = this;
//Set the varaiable to an empty array to receive the data
DashboardCards.DashboardCards = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardCards.DashboardCards = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card) {
//Declare a varaible for the data
var DashboardMetrics = this;
//Set the varaiable to an empty array to receive the data
DashboardMetrics.DashboardMetrics = [ ];
$http({
//Request the data
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + **???reference to parent card ID???** + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
//The data was sucessfully received, populate the variable with it
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
//There was an error
console.log('Metric data could not be retrieved');
});
}]);
})();
Thank you!
EDIT 1
Use a service for shared variable between controllers. Look the example:
app.controller('DahsboardCardController', ['$http', function($http, $sharedResource) {
var DashboardCards = this;
DashboardCards.DashboardCards = [ ];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/tbl_Card',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardCards.DashboardCards = data.data.d.results;
$sharedResource.set("id", "<pass id value>");
}, function errorCallback(response) {
console.log('Card data could not be retrieved');
});
}]);
app.controller('DahsboardMetricController', ['$http', function($http, Card, $sharedResource) {
var DashboardMetrics = this;
DashboardMetrics.DashboardMetrics = [];
$http({
method: 'GET',
dataType: 'jsonp',
url: '/api.svc/DashboardMetric?Card=%27' + $sharedResource.get("id") + '%27',
useDefaultXhrHeader: false,
headers: {'Content-type': 'application/json'},
headers: {'Accept': 'application/json;odata=light;q=1,application/json;odata=verbose;q=0.5'},
crossDomain: true,
}).then(function successCallback(data) {
DashboardMetrics.DashboardMetrics = data.data.d.results;
}, function errorCallback(response) {
console.log('Metric data could not be retrieved');
});
}]);
app.factory('$sharedResource', function () {
var property = {};
return {
get: function (key) {
return property[key];
},
set: function(key, value) {
property[key] = value;
}
};
});
EDIT 2
When working with angularjs is recomended use a one object for print object in table. Why this is a beautiful s2.
Look this example. To help you in development. Use the sample function pass the parentId in load(CardId). This function will run in the page load.
I too fix code html. You used the alias controller before input field of same.
var app = angular.module("App", []);
app.controller('DahsboardCardController', ['$scope', function($scope) {
$scope.DashboardCards = [{
CardId: "111",
CardDisplayName: "Card 1"
}, {
CardId: "222",
CardDisplayName: "Card 2"
}, {
CardId: "333",
CardDisplayName: "Card 3"
}];
}
]);
app.controller('DahsboardMetricController', ['$scope', function($scope) {
$scope.load = function(CardIdParent) {
console.log(CardIdParent);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" class="Dashboard container-fluid" ng-controller="DahsboardCardController as Dashboard">
{{Dashboard.DashboardCards}}
<div ng-repeat="Card in DashboardCards">
<div class="DashboardCard card">
{{Card.CardDisplayName}}
<div class="DashboardCardBody" ng-controller="DahsboardMetricController as Metric" ng-init="load(Card.CardId)">
This a id parent: {{Card.CardId}}
<div ng-repeat="MetricItem in DashboardMetrics">
{{MetricItem.MetricDisplayName}}
</div>
</div>
</div>
</div>
</div>