14

我在我的项目中使用 KnockoutJS,但我想学习 AngularJS,因为它有很多 Knockout 没有的美味功能。所以我对使用 Angular 重写我的一些代码很感兴趣。但我不明白如何做一些我在 Knockout 中使用的简单事情。例如,Knockout 具有计算 observables 的功能。这个很酷!我已经发现我可以使用一个简单的函数来代替。但是 Knockout 为计算的 observables 提供了“写入”功能,例如:

var first_name = ko.observable('John'),
    last_name = ko.observable('Smith'),
    full_name = ko.computed({
        read: function(){
            return first_name() + ' ' + last_name();
        },
        write: function(new_value){
            var matches = new_value.match(/^(\w+)\s+(\w+)/);

            first_name(matches[1]);
            last_name(matches[2]);
        }
    });

JSFiddle 上的这段代码:http: //jsfiddle.net/Girafa/QNebV/1/

这段代码允许我在更改“full_name”时更新“first_name”和“last_name”observables。如何使用 AngularJS 来完成?一个带有参数的函数被检查是否存在?像这样的东西?

first_name = 'John';
last_name = 'Smith';
full_name = function(value){
    if (typeof value != 'undefined')
    {
        // do the same as in the Knockout's write function
    }
    else
    {
        // do the same as in the Knockout's read function
    }
}

最佳做法是什么?

4

2 回答 2

12

我找到了这样的解决方案:http: //jsfiddle.net/Girafa/V8BNc/

我们没有使用 angular $watch 方法,而是设置了 fullName 属性的原生 javascript getter 和 setter:

Object.defineProperty($scope, 'fullName', {
    get: function(){
        #...
    },
    set: function(newValue){
        #...
    }
})

认为这更方便,因为我不需要在代码中创建任何特殊的观察者。但我不知道该解决方案的浏览器支持。

于 2013-10-23T17:55:30.277 回答
0

对于那个很抱歉。确实,这在淘汰赛中更简单,因为在 angular 中调用了函数而使用了属性。这是我可以解决的方法,但我想知道是否有更好的方法。

我这次修好了Plunker

app.controller('Ctrl', function($scope) {
    $scope.firstName = 'John';
    $scope.lastName  = 'Smith';

    $scope.getFullName = function() {
        $scope.fullName = $scope.firstName + ' ' + $scope.lastName;
        return $scope.fullName;
    }

    $scope.$watch('fullName', function(newValue, oldValue) {
        var names = newValue.split(' ');
        $scope.firstName = names[0];
        $scope.lastName  = names[1];  
    });
});
于 2013-10-22T21:21:07.613 回答