javascript - Angular JS 使用 ngInit 定义变量

标签 javascript php angularjs

基本上,我将变量从 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/

相关文章:

javascript - Node.js CPU 负载平衡多个 CPU 内核上的 Websocket 客户端

javascript - 哪些选项可用于通过 JavaScript 开发工具包对 AWS 用户进行身份验证?

php - MySQL 中的时间戳问题

java - Angularjs 到 spring Controller

javascript - JQUERY:单击错误时增加文本区域高度

javascript - 如何在 jquery 就绪函数中获取 URL 参数?

php - Ajax 调用 php 脚本返回 404 错误

php - 使用 mssql php 在 SQL 数据库中插入文件内容时出错

javascript - $compile 显示未捕获的 TypeError : undefined is not a function

javascript - 在http错误回调中访问 'this'