How to trigger an update of NgComponent when child

2020-04-20 19:07发布

I am a complete beginner to AngularDart (and Dart); I followed the tutorials but this is something I can't seem to find a answer to.

I have two NgComponents that work perfectly:

 <colorImage car-color="ctrl.car.color"></colorImage>
 <carImage car="ctrl.car"></carImage>

My controller "ctrl" has a property named "car" and "car" has a property named "color". When "car.color" changes, the colorButton NgComponent updates, but the carImage NgComponent does not.

How can I trigger an update of carImage when "car.color" changes?

Thanks!!

2条回答
\"骚年 ilove
2楼-- · 2020-04-20 19:37

Here is working example without a scope and a watch features. I believe this is an angulardartish solution.

Something more about the issue: https://stackoverflow.com/a/21958268/2777805

ang_testi.dart

import 'package:angular/angular.dart';

@NgComponent(
 selector: 'colorImage',
 template: r'<p>colorImage: <input type="text" ng-model="cmp.carColor"></p>',
 publishAs: 'cmp'
)
class colorImage {
  @NgTwoWay('car-color')
  String carColor;
}

@NgComponent(
    selector: 'carImage',
    template: r'<p>carImage: <input type="text" ng-model="cmp.car.color"></p>',
    publishAs: 'cmp'
)
class carImage {
  @NgTwoWay('car')
  Map car;
}

@NgController(
    selector: '[main-test]',
    publishAs: 'ctrl')
class MainTestController {
  Map car = {"color":"green", "image":"someImage"};
}

class MyAppModule extends Module {
  MyAppModule() {
    type(MainTestController);
    type(colorImage);
    type(carImage);
  }
}

void main() {
  ngBootstrap(module: new MyAppModule());
}

ang_testi.html

<!DOCTYPE html>

<html ng-app>
  <head>
    <meta charset="utf-8">
    <title>ng-model test</title>
    <link rel="stylesheet" href="ang_testi.css">
  </head>
  <body main-test>
    <colorImage car-color="ctrl.car.color"></colorImage> 
    <carImage car="ctrl.car"></carImage> 

    <p>controller: <input type="text" ng-model="ctrl.car.color"></p>
    <p>color is {{ctrl.car.color}}</p>

    <script src="packages/shadow_dom/shadow_dom.min.js"></script>
    <script type="application/dart" src="ang_testi.dart"></script>
    <script src="packages/browser/dart.js"></script>
  </body>
</html>
查看更多
女痞
3楼-- · 2020-04-20 19:57

You have to set a watch to car.color inside your CarImage. How this looks depends on what data structure you use for car.

// constructor
CarImage(Scope scope) {
   scope.$watch(() => car.color, (color) => doSomething(color));
}
查看更多
登录 后发表回答