基本上,我将变量从 PHP 发送到 Angular JS。我将 PHP 变量回显到 ng-init 标记中,并且它正确呈现(ng-init="listing=5;user=59")。
<div id="content" ng-app="galleryApp" ng-controller="galleryController"
ng-init="listing=<?php echo $lid ?>;user=<?php echo $sessionUser ?>">
但是,在我的 Angular JS 代码中,当我记录变量时,它们显示为未定义。
var galleryApp = angular.module('galleryApp', []);
function galleryController ($scope, $http, $log) {
console.log($scope.listing); // <-- undefined
console.log($scope.user); // <-- undefined
var postData = { listing : $scope.listing, user: $scope.user };
最佳答案
Controller 的构造函数在ng-init
之前调用。如果您考虑一下, Controller 的 $scope
必须先存在,然后 ng-init
才能向其中添加内容。
如果将 $watch
添加到 Controller 范围的属性中,如果所有设置都正确,您应该会看到它发生变化:
function galleryController ($scope, $http, $log) {
$scope.$watch('listing', function(value) { console.log(value); });
$scope.$watch('user', function(value) { console.log(value); });
var postData = { listing : $scope.listing, user: $scope.user };
关于javascript - Angular JS 使用 ngInit 定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26021412/