TAGS :Viewed: 1 - Published at: a few seconds ago

[ Model Id passed through to Angular Ctrl ]

I have a MVV view that used the Controller below, I need to get the product Id, ie Model.Id through to the controller somehow. I have tried the $scope.init but it is coming through as null when I am making the first Ajax call, I suspect that this ajax get is kicking off before the init is fired and setting the product id, so the ajax fails as the productId is null when the call is made. I am new to angular so if its a schoolboy error I apologise !.

Controller and HTML are shown below.

 angular.module('askQuestions', [])
 .controller('questionController', function ($scope, $http) {
  $scope.loading = true;
  $scope.addMode = false;
  $scope.replyMode = false;
  $scope.parentClicked = 0;

  $scope.init = function (productId) {
      //This function is sort of private constructor for controller
      $scope.productId = productId;
      $scope.getUrl = '/Api/GetProductQuestions/' + $scope.productId;

  };


  //Used to display the data
  //$http.get('/Api/GetAllManufacturers?apiToken=6a5ce02e-0506-0a41-2f50-37327080662f').success(function (data) {
  $http.get($scope.getUrl).success(function (data) {


      $scope.questions = data;
      $scope.loading = false;

  })
  .error(function () {
      $scope.error = "An Error has occured while loading questions!";
      $scope.loading = false;
     // alert($scope.getUrl);
  });

});

<div data-ng-app data-ng-controller="questionController" ng-init="init('@Model.Id')" class="container">

Answer 1


Your $http.get is evaluated in the instantiation of the controller. The instantiation is before your init, so the ajax call is already being made. You can easily fix this by wrapping your $http.get also in a function:

$scope.init = function (productId) {
    //This function is sort of private constructor for controller
    $scope.productId = productId;
    $scope.getUrl = '/Api/GetProductQuestions/' + $scope.productId;
    getData();
};

var getData = function() {
    $http.get($scope.getUrl)
        .success(function (data) {
            // success
            $scope.questions = data;
        })
        .error(function () {
            // error
            $scope.error = "An Error has occured while loading questions!";
        })
        .finally(function () {
            // always
            $scope.loading = false;
        });
}