繁体   English   中英

在Angular JS文件中获取未定义的PHP值

[英]getting undefined php value in angular js file

我在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文件中,我得到了正确的值。

<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的位置,以便可以在页面加载后立即初始化变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM