1

I have a php session variable set in index.php file. Using ng-init I am assigning that session value to a variable so that I can use in my angularjs controller file. This is my index.php file

<body ng-app="myApp">
    <div ng-controller="restaurantController" ng-init="total=0;something='<?php echo $_SESSION['rname'] ?>'" class="container">
        <div class="col l4 s4 container">
        <label>Search</label>    <input type="text" ng-model="search.name">
    </div>
        <div ng-repeat="item in items | filter:search" class="container">
            <h3>{{item.name}}</h3>
            <p>category:{{item.category}}</p>
            <p>price:INR {{item.price}} /-</p>
            <br/>
            <button ng-hide="item.added"  ng-click="process(item)">Add</button>
            <button ng-show="item.added" class="ng-cloak">Remove</button>
        </div>
        <h1>Total:<span ng-model="total">{{total}}</span></h1>
    </div>
    <script src="../angular/app.js"></script>
    <script src="../angular/restaurantController.js"></script>
    <script src="../materialize/js/materialize.min.js"></script>
</body> 

Here the variable something is assigned to a php session variable. But I am getting undefined when I use $scope.something in controller file. This is my controller file

var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController',['$scope','$http', function($scope, $http){
    $http.get($scope.something+'.json').success(function (data){
        $scope.items = data;
    });

    $scope.process = function(item){
        $scope.total = parseInt($scope.total) + parseInt(item.price);
        item.added=true;
    }
}]);

The value of $scope.something is undefined in controller file but in php file I am getting the correct value.

Rohan Kushwaha
  • 738
  • 6
  • 18
Gopal Chandak
  • 387
  • 7
  • 19

1 Answers1

0
<body ng-app="myApp" ng-init="total=0;something='<?php echo $_SESSION['rname'] ?>'">
    <div ng-controller="restaurantController"  class="container">
        <div class="col l4 s4 container">
        <label>Search</label>    <input type="text" ng-model="search.name">
    </div>
        <div ng-repeat="item in items | filter:search" class="container">
            <h3>{{item.name}}</h3>
            <p>category:{{item.category}}</p>
            <p>price:INR {{item.price}} /-</p>
            <br/>
            <button ng-hide="item.added"  ng-click="process(item)">Add</button>
            <button ng-show="item.added" class="ng-cloak">Remove</button>
        </div>
        <h1>Total:<span ng-model="total">{{total}}</span></h1>
    </div>
    <script src="../angular/app.js"></script>
    <script src="../angular/restaurantController.js"></script>
    <script src="../materialize/js/materialize.min.js"></script>
</body> 

Got the solution. just had to change the position of ng-init so that the variables can e initialized as soon as the page loads.

Gopal Chandak
  • 387
  • 7
  • 19