Angular $ watch不更新绑定

时间:2015-02-19 18:31:26

标签: javascript angularjs

我正在尝试为某些模型属性提供默认值,并尝试使用$ watches完成此操作。我不能使用普通的2路绑定,因为我需要模型属性最初为空。但是,虽然我的$ watches正在设置属性ok,但是绑定到它们的HTML没有得到更新。

<!doctype html>
<body ng-app="TestApp" ng-controller="TestCtrl">
    <div><input ng-model="form.firstname" placeholder="enter your first name"/></div>
    <div><input ng-model="form.lastname" placeholder="enter your last name"/></div>    
    <p>{{user.firstname}}</p>
    <p>{{user.lastname}}</p>
</body>

angular.module('TestApp', [])
.controller('TestCtrl', ['$scope', function($scope) {

    $scope.user = new User({
        firstname: 'Bruce',
        lastname: 'Wayne'
    });

    function User(defaults) {
        angular.extend(this, defaults);
        $scope.form = {};

        angular.forEach(this, function(value, key) {
            $scope.form[key] = '';

            $scope.$watch(function() {
                return $scope.form[key];
            }, function (val) {
                this[key] = val || defaults[key];
                console.log(val)
                console.log(defaults[key])
                console.log(this[key])
            });
        });
    }
}]);

查看小提琴here - 我想要的是在框中输入的任何值都会反映在文本中,然后如果删除该值,则默认文本会再次显示。如果您检查控制台,您将看到手表回调正常工作。我确实尝试将更新包装在$ apply中,但是获得了$ digest in progress错误。

角度相当新,所以我可能会错误地尝试完成此操作!

1 个答案:

答案 0 :(得分:1)

问题是this运行时$watch会发生变化。

    function User(defaults) {
        angular.extend(this, defaults);
        $scope.form = {};

        var self = this; // <-- Saving `this`.

        angular.forEach(this, function(value, key) {
            $scope.form[key] = '';

            $scope.$watch(function() {
                return $scope.form[key];
            }, function (val) {
                self[key] = val || defaults[key];
                console.log(val)
                console.log(defaults[key])
                console.log(self[key])
            });
        });

保存this解决了问题:http://jsfiddle.net/637yypz1/1/

相关问题