简体   繁体   中英

Angular JS Defining a Variable with ngInit

Basically I'm sending a variable from PHP to Angular JS. I echo the PHP variables into the ng-init tag, and it renders properly (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 ?>">

However, in my angular JS code, when I log the variables, they come up as undefined.

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 };

The controller's constructor function is called before ng-init . If you think about it, the controller's $scope has to exist before ng-init can add things to it.

If you add a $watch to the properties on the controller's scope, if all is set up correctly, you should see it change:

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 };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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