我在index.php文件中设置了一个php会话变量。使用ng-init我将该会话值分配给变量,以便我可以在我的angularjs控制器文件中使用。 这是我的index.php文件
<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>
这里将变量分配给php会话变量。 但是当我在控制器文件中使用$ scope.something时,我得到了未定义。 这是我的控制器文件
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;
}
}]);
$ scope.something的值在控制器文件中未定义,但在php文件中我得到了正确的值。
答案 0 :(得分: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>
得到了解决方案。只需更改ng-init的位置,以便在页面加载后立即初始化变量。