What is the analog for Knockout's writable computed observable in AngularJS?

前端 未结 2 1692
礼貌的吻别
礼貌的吻别 2021-02-05 14:17

I use KnockoutJS in my projects, but want to learn AngularJS as it has a lot of tasty features that Knockout doesn\'t have. So I\'m interested in rewriting some of my code using

相关标签:
2条回答
  • 2021-02-05 14:26

    I've found such a solution: http://jsfiddle.net/Girafa/V8BNc/

    Instead of using angular $watch method, we set native javascript getter and setter of the fullName property:

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

    Think this is more convenient as I don't need to make any special watchers in the code. But I don't know about browser support of this solution.

    0 讨论(0)
  • 2021-02-05 14:34

    Sorry about that. It's true, this is simpler in knockout because a function is called whereas a property is used in angular. This is the way I could resolve it, but I would like to know if there is a better way.

    I fixed this time 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];  
        });
    });
    
    0 讨论(0)
提交回复
热议问题