thb7
thb7

Reputation: 125

Angular JS Controller - Scope issue (maybe)

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.

Upvotes: 0

Views: 41

Answers (2)

Indranil Mondal
Indranil Mondal

Reputation: 2857

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.

Upvotes: 2

dr-
dr-

Reputation: 113

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).

Upvotes: 0

Related Questions