AngularJS ng-show is true, but display: none
I have two buttons on a page that do basically the same thing. Button 1 fetches a string and displays it in a div. Button 2 fetches the same line and outputs it to the same div, but it also fetches the status code. Only one button can be pressed per page reload. Below is the version of my controller:
angular.module('myModule', []).controller('myController', [ '$scope', function($scope) {
self = this;
this.loaded = false;
this.msg = '';
this.getMessage = new Object(blah...);
this.getMessage.success = function(data) {
self.loaded = true;
self.msg = data.msg;
$scope.$apply(function() {
self;
});
};
this.getStatus = new Object(blah...);
this.getStatus.success = function() {
self.getMessage();
};
this.button1.click(function() {
$.ajax(self.getMessage);
});
this.button2.click(function() {
$.ajax(self.getStatus);
});
}]);
I am using jQuery for the AJAX calls because I am switching from jQuery to Angular and I am working up front to get all the jQuery. So far, my page looks something like this:
<DOCTYPE html>
<html>
<head>
<!-- js/css inclusions -->
</head>
<body>
<div ng-controller='myController as ctrl'>
<div ng-show='ctrl.loaded' ng-bind='ctrl.msg'></div>
</div>
</body>
</html>
On page load, my div looks like this:
<div class='ng-hide'
ng-show='ctrl.loaded'
ng-bind='ctrl.msg'
style='display: none'></div>
When button 1 is clicked, my div turns into:
<div class=''
ng-show='ctrl.loaded'
ng-bind='ctrl.msg'
style=''>Message Here.</div>
On button 2 click my div turns into:
<div class=''
ng-show='ctrl.loaded'
ng-bind='ctrl.msg'
style='display: none'>Message Here.</div>
This div is not used by me, just the default CSS from Angular to show / hide things. My question is, am I doing something wrong? Is there some problem that I am not seeing? Is there something else that I am not doing right (the Angular way)?
Edit : Injected $scope
service into my controller, but still the same result.
source to share
Since HTTP calls are made with jQuery instead of using an Angular service $http
, Angular doesn't know that your parameter is loaded
changing and therefore doesn't update the view.
Wrap the code inside success callbacks in a block $scope.$apply
as shown below so that Angular knows it needs to update the viewport when you make your changes to the parameters. You will also need to inject the service $scope
into your controller.
this.getMessage.success = function(data) {
$scope.$apply(function () {
self.loaded = true;
self.msg = data.msg
});
};
Also, you have to use a service $scope
to inject parameters into your view - whatever is there.
source to share