简体   繁体   中英

AngularJs $watch Why isn't this working?

I'm trying to get values to update in reverse in this AngularJs script i'm writing here: http://jsfiddle.net/flashpunk/tR5Mr/1/

$scope.$watch('watchList', function(newV,oldV) {
    console.log('change');
    $scope.main.right.assets = addAssets();
    $scope.main.right.roa = roaCalc();
    $scope.main.right.target = targetCalc();
}, true);

You can see that you can change the values in the Slide1, Slide2, Slide3, Slide4, and Slide5 input boxes which effect the MAIN input boxes, however the watch function doesn't seem modify the Slide boxes when the MAIN boxes are modified.

Can anyone help me make this work? Ive been racking my brains for hours on this.

Try,

$scope.$watch(function() {
    return $scope.watchList;
}, function (newV, oldV) {
    console.log('change');
    $scope.main.right.assets = addAssets();
    $scope.main.right.roa = roaCalc();
    $scope.main.right.target = targetCalc();
}, true);

Demo

Your watch is working. It's being triggered by changes to any of the boxes.

The issue is your watch only computes values for your main boxes when triggered. You need to detect what values changed (slide or main) and calculate in the appropriate direction based on which changed..

The easiest solution may be two watches- the one you currently have stays watching all the slide boxes. So that watchlist will now look like:

$scope.watchList = [
    $scope.slide1,
    $scope.slide2,
    $scope.slide3,
    $scope.slide4,
    $scope.slide5   
];

And a new watch which watches the main and updates the slide boxes.

$scope.$watch('main', function(newV,oldV) {
    console.log('main changed');
    //Update any slide values that need updating here
}, true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM