how to access to a $scope value into a controller

时间:2015-05-24 20:37:55

标签: angularjs

can someone explain me why i cannot get the $scope.pk value in my console.log()

'use strict';

angular.module('angularDjangoRegistrationAuthApp')
  .controller('TweatCtrl', function ($scope, $location, djangoAuth, djangoTweat, $routeParams) {
    $scope.tweek = function(){
        console.log(' tweek ');
    };

    djangoAuth.profile().then(function(data){
        $scope.user = data;
        $scope.pk = data.pk;
    });

    djangoTweat.getUserTweeks(1)
        .then(function(data){
            $scope.tweeks = data
        },function(data){
            // error case
            $scope.errors = 'no tweeks';
        });
    console.log($scope);
    console.log($scope.pk);

The fisrt console.log() returns me the Scope object with a pk value. The second console.log() returns 'undefined' :(

2 个答案:

答案 0 :(得分:4)

You are trying to access $scope.$pk before it is set.

The following code is probably run asynchronously, as it is using promises. It will run some time after the console.log statements at the end of your controller initialization. It will only run if the djangoAuth.profile() promise is resolved (succeeds).

djangoAuth.profile().then(function(data){
    $scope.user = data;
    $scope.$pk = data.pk;
    // now log $scope.$pk after it is set (assuming data.pk is not undefined)
    console.log("$scope.$pk is", $scope.$pk, "and data.pk is", data.pk);

});

答案 1 :(得分:-1)

i saw a declaration of $pk, your're trying to log a pk attr of $scope..

Console.log($scope.$pk); //it should be ok..

Another thing, i suggest you to use $log, and include it in the function of the controller, then, you'll be able to use $log.Error, $log.Debug and $log.log to the standard console..