I have the following in my HTML:
<body ng-controller = "Control as control">
<button ng-click = "control.prepareAction()">Do Action </button>
<div id="one" ng-hide = "!control.showOne" >
<div>
<h6> {{control.name}}</h6>
<p> Bills Sponsored: {{control.count}} <p>
</div>
</body>
And in my Javascript:
var vm = this;
vm.name = "My Name"
vm.prepareAction = function(){
action(parseFirst(), parseLast()); //The two parse functions simply get values from an HTML form. This works correctly.
}
function action(first, last) {
$.post('php/one.php', {
first: first,
last: last
},
function(data) {
create(JSON.parse(data));
});
return values;
}
function create(data) {
var countArray = data[0];
vm.count = countArray[0];
vm.showOne = true;
}
This function does not update the values of showOne (the div is always hidden) or count (it is blank when I set ng-hide to false) in the HTML. However, when I set ng-hide to false, it shows the name correctly. This makes me think it is a scope issue, however, when I print the value of vm to the console, the values for showOne and count are correct. This is confirmed by the Chrome ng-inspector Extension.
-
You need to check few things, first check if the post request is being successful and it's calling the create function or not and also check instead of using $.post use the $http service of angular. And try to use $scope.$apply() in the last line of the create function and if it works then obviously it's a issue with the $.post itself.Indranil Mondal– Indranil Mondal2015年12月04日 19:04:46 +00:00Commented Dec 4, 2015 at 19:04
-
I can definitely confirm that create is being called because when I console.log(vm) it shows the correct value of count and shows showOne as true. Should I still try angular's HTTP?thb7– thb72015年12月04日 19:08:23 +00:00Commented Dec 4, 2015 at 19:08
2 Answers 2
Actually you're using $.post which is outside of the context of angular js thus from the create method the digest cycle is working properly. So to solve it there is two options.
Either instead of $.post you need to use
$http({
method: 'POST',
url: 'php/one.php'
}).then(function successCallback(response) {
create(JSON.parse(response));
}, function errorCallback(response) {
});
Or you need to modify the create function a little
function create(data) {
var countArray = data[0];
vm.count = countArray[0];
vm.showOne = true;
$scope.$apply();
}
And in both case you need to inject $http & $scope in the controller accordingly.
Comments
Try adding your update function to vm.
vm.action = action;
If you don't do this, it cannot be called outside of the closure (i.e. in your html).