How to change AngularJS data outside the scope?

前端 未结 6 531
梦谈多话
梦谈多话 2020-12-05 04:33

After hours of frustrating searches I feel I need to submit my question here. I apologize in advance if this question is somehow answered before but none of my searches has

6条回答
  •  攒了一身酷
    2020-12-05 04:51

    Jeremy's answer is really good, though now Angular has changed, and will no longer work, unless you add this line of code:

    $scope = $scope.$$childHead;
    

    So, the changed function should look like this

    function change() {
        var appElement = document.querySelector('[ng-app=myApp]');
        var $scope = angular.element(appElement).scope();
        $scope = $scope.$$childHead; // add this and it will work
        $scope.$apply(function() {
            $scope.data.age = 20;
        });
    }
    

提交回复
热议问题