tonymx227
tonymx227

Reputation: 5451

Init variable using AngularJS

I'd like to init a variable using AngularJS in my template... It seems not working.

Template :

<div class="eventList" ng-controller="EventOfCategoryController">
  <input type="hidden" ng-init="categoryId = <%=id%>" />
</div>

Js :

app.controller("EventOfCategoryController", function($scope, $http, $filter) {
  console.log($scope.categoryId); //undefined
  $http.get('/category/'+$scope.categoryId).success(function(data, status, headers, config) {
      // my functions
  });
});

Upvotes: 1

Views: 988

Answers (4)

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

You are trying to read the set value before Angular is done assigning.

app.controller("EventOfCategoryController", function($scope, $http, $filter) {
  $timeout(function(){
        console.log($scope.categoryId);
    },1000);
  $http.get('/category/'+$scope.categoryId).success(function(data, status, headers, config) {
      // my functions
  });
});

Ideally you should use $watch as bellow if you need to use ng-init at all:

app.controller("EventOfCategoryController", function($scope, $http, $filter) {
    console.log('test');
    $scope.$watch("categoryId", function(){
        console.log($scope.categoryId);
$http.get('/category/'+$scope.categoryId).success(function(data, status, headers, config) {
      // my functions
  });
    });
});

You can also use a method in you ng-init as follows. This will reduce watch load and increase performance.

app.controller("EventOfCategoryController", function($scope, $http, $filter) {
        console.log('test');
        $scope.init = function(categoryId){
            console.log(categoryId);
    $http.get('/category/'+categoryId).success(function(data, status, headers, config) {
          // my functions
      });
        });
    });

And ng-int as

<input type="hidden" ng-init="init(<%=id%>)" />

Upvotes: 2

Jack
Jack

Reputation: 329

If you wrap console.log in a setTimeout and utilise a $scope.$apply, categoryId will become available:

    setTimeout(function () {
        $scope.$apply(function () {
            console.log($scope.categoryId); // 7
        });
    }, 0);

Upvotes: 0

rupesh_padhye
rupesh_padhye

Reputation: 1405

The controller(EventOfCategoryController) is being created before the categoryId variable is added to the $scope object.

$scope.$watch('categoryId', function () {
    console.log($scope.categoryId); 
});

Upvotes: 0

Andr&#233; Kreienbring
Andr&#233; Kreienbring

Reputation: 2509

you shoud init the variable in your controller:

app.controller("EventOfCategoryController", function($scope, $http, $filter) {
  $scope.categoryId = 7;  
  console.log($scope.categoryId); //undefined
  $http.get('/category/'+$scope.categoryId).success(function(data, status, headers, config) {
      // my functions
  });
});

And

<input type="hidden" ng-model="categoryId">

Upvotes: 0

Related Questions