How to set scope property with ng-init?

前端 未结 6 455
借酒劲吻你
借酒劲吻你 2020-11-30 02:26

I am trying to set the value of a $scope property using ng-init, and I am unable to access that value in the controller\'s javascript. What am I doing wrong? Here is a fidd

6条回答
  •  野性不改
    2020-11-30 03:04

    You are trying to read the set value before Angular is done assigning.

    Demo:

    var testController = function ($scope, $timeout) {
        console.log('test');
        $timeout(function(){
            console.log($scope.testInput);
        },1000);
    }
    

    Ideally you should use $watch as suggested by @Beterraba to get rid of the timer:

    var testController = function ($scope) {
        console.log('test');
        $scope.$watch("testInput", function(){
            console.log($scope.testInput);
        });
    }
    

提交回复
热议问题