Why is the variable set in ng-init undefined in $scope in AngularJS?

前端 未结 4 1290
难免孤独
难免孤独 2020-12-29 19:58

I have a variable I\'m setting in my view with ng-init which I am then trying to access in my controller. When I try to access it however, I\'m getting an

相关标签:
4条回答
  • 2020-12-29 20:18

    You can also take advantage of how JavaScript defines functions and use a function for ng-init instead of $watch (jsfiddle).

    <div ng-app>
        <div ng-controller="MyCtrl" ng-init="pageTitleEquals('kittens')">
            Page title is {{ pageTitle }}
        </div>
    </div>
    

    Controller:

    var MyCtrl = function($scope) {   
        $scope.pageTitleEquals = function(title) {
            $scope.pageTitle = title;
        }
    };
    

    This question is similar: How to set scope property with ng-init?

    0 讨论(0)
  • 2020-12-29 20:19

    the controller is being created before the pageTitle variable is added to the $scope object.

    0 讨论(0)
  • 2020-12-29 20:29

    Wait until the variable is init.

    $scope.$watch('pageTitle', function () {
        console.log($scope.pageTitle); 
    });
    
    0 讨论(0)
  • 2020-12-29 20:31

    Since you are doing a "single time init", like a constructor I recommend you to unbind the watch after using the variable:

    var pageTitleWatch = $scope.$watch('pageTitle', function () {
        console.log($scope.pageTitle);
        // Now just unbind it after doing your logic
        pageTitleWatch();
    });
    
    0 讨论(0)
提交回复
热议问题