New to Angular - Computed Variables

前端 未结 7 1515
一个人的身影
一个人的身影 2021-02-04 00:33

I am moving to Angular from Knockout, and I have a few issues. I\'m assuming that I must be doing something a non-angular type of way.

http://jsfiddle.net/LostInDaJungle

7条回答
  •  误落风尘
    2021-02-04 01:24

    Ok,

    A few hours later and I think I have my answer.

    Using $scope.$watch.

    $scope.$watch('(height * width) * 40', function(v) {$scope.cost = v;});
    

    or

    $scope.$watch('height + width', function() {$scope.cost = (Number(height) * Number(width)) * 40;});
    

    This auto-updates any computables for watched variables. And it gives me a way to work with these without having to live inside curly brackets.

    Also, the computed values can be reused and tracked for cascading updates:

    $scope.$watch('height * width', function(v) {$scope.dim = v;});
    $scope.$watch('dim * 40', function(v) {$scope.cost = v;});
    

    So if height and/or width change, dim is updated, and since dim has changed, cost is updated.

提交回复
热议问题