0

I am trying to fetch records via ajax and displaying using AngularJS. But my code even not invoking controller action.

I am trying this code..

<div ng-controller="MyCtrl">
<div ng-repeat="result in products">
    {{result.ProductName}}
</div>
</div>

Ajax :

function MyCtrl($scope) {
  $.ajax({
    url: "/Products/Get/",
    type: "POST",
    success: function (data) {
      // Success message
      var myApp = angular.module('myApp', []);
      $scope.products = data;
    },
    error: function () {
      // Fail message
    },
  });
}

I am using this post to make it work.

1
  • You don't have controller MyCtrl Commented Jul 24, 2016 at 11:01

2 Answers 2

2

Your approach is wrong. You should use angularJS's controller directive to invoke services to consume json data.

<script type="text/javascript">
    var app = angular.module('myApp', []); 
    app.controller('MyCtrl', function ($scope, $http) {  
        $http.get('/Products/Get/').success(function (data) {  
            $scope.products = data;
        });
    });
</script>

I had written an article few days ago on the same. You can go through here. This might be helpful.

Sign up to request clarification or add additional context in comments.

1 Comment

Since success is deprecated you should use then instead of success.
0

you need declare module name in angularjs , and dont forget to add module name in you body or html tag..like this <body data-ng-app="app"> and then Try like this :

<script>
var app = angular.module('app',[]);

app.controller('MyCtrl',function($scope,$http){

bindData();
function bindData(
    // it will be nice, if this code your separate to file service...    
    $http.get('/Products/Get').success(function (callBack) {  
            $scope.products = callBack.data;
    });
);
});

</script>

and Best Implementation like This :

// in controller, injected you service name like this..
app.controller('MyCtrl',function($scope,$http ,myServices){

bindData();
function bindData(
  var promiseGet = myServices.GetAll();
  promiseGet.then(function(callBack){ // success
    $scope.products = callBack.data;

   }     
 ,function(error){ // error
     console.log(error);
   });
 );    

});

app.service('myServices',function($http){
var vm = this;
vm.GetAll = function(){
         return $http.get('/Products/Get');
     }
});

and type not POST, if you want to Get data in ajax function..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.