为什么这不绑定?

The*_*rby 1 binding angularjs

我正在学习有关角度的一切.我知道有很多关于角度绑定的SO问题,但我仍在苦苦挣扎.也许有人可以通过这个例子给我一些清晰度.

        .controller('myCtrl',['$scope',function($scope){

            //define dummy usermanager "class" 
            var um = function(){
                this.username = 'myUsername';
            };

            //init dummy user class 
            var _um = new um();

            //Bind usermanager to scope 
            $scope.UserManager = _um;

            //After three seconds set new username 
            setTimeout(function(){
                console.log('set');
                _um.username = 'newUsername';
            },3000);
        }]);
Run Code Online (Sandbox Code Playgroud)

使用基本模板

<p>{{ UserManager }}</p> 
Run Code Online (Sandbox Code Playgroud)

在此示例中,它将始终显示为{username:myUsername},并且永远不会更改为{username:newUsername}

如何在此示例中正确使用Angulars双向绑定?

编辑: 看来我可以使用$ scope.$ apply(); 但这似乎不是最好的方法.

use*_*281 11

正如其他人所指出的,角度不知道变化$scope.您应该使用$timeout而不是将您的函数包装在一个$apply

$timeout(function() {
    console.log('set');
     _um.username = 'newUsername';
}, 3000);
Run Code Online (Sandbox Code Playgroud)