Dart Example

AngularDart v4 Service

AngularDart v4 Sample Code,Demo
Loading…
(html)
<head>
.....
  <script defer src="main.dart" type="application/dart"></script>
  <script defer src="packages/browser/dart.js"></script>
</head>
<body>
  <my-app>Loading...</my-app>
</body>

(pubspec.yaml)
.....
environment:
  sdk: '>=1.24.0 
    
(main.dart)
import 'package:angular/angular.dart';
import 'log_service.dart';

@Component(
  selector: 'my-sub',
  template: '''
<h4>{{sub_name}}</h4>
<ul>
  <li *ngFor="let item of logs">
    {{item['id']}}=>{{item['msg']}}
  </li>
</ul>
<button (click)="addlog(sub_name + ':test log')">Write a log</button>
    ''',
  directives: const [CORE_DIRECTIVES],
//  providers: const [LogService]
)
class MySub {
  final LogService _logService;
  @Input() String sub_name;
  List logs;
  MySub(this._logService) {
    this.logs = this._logService.listlogs();
  }
  void addlog(String msg) {
    this._logService.addlog(msg);
  }
}

@Component(
  selector: 'my-app',
  template: '''
<button (click)="open('Sub-A')">Sub-A</button>
<button (click)="open('Sub-B')">Sub-B</button>
<div [ngSwitch]="tab">
  <div *ngSwitchCase="'Sub-A'">
    <my-sub [sub_name]="'Sub-A'"></my-sub>
  </div>
  <div *ngSwitchCase="'Sub-B'">
    <my-sub [sub_name]="'Sub-B'"></my-sub>
  </div>
</div>
    ''',
  directives: const [CORE_DIRECTIVES, MySub]
)
class AppComponent {
  String tab = 'Sub-A';
  void open(String tab) {
    this.tab = tab;
  }
}

void main() {
  bootstrap(AppComponent, [LogService]);
}


(log_service.dart)
import 'package:angular/angular.dart';

@Injectable()
class  LogService {
  List _logs = [];
  int _logCount = 0;

  List listlogs() {
    return this._logs;
  }

  void addlog(String msg) {
    var log = new Map();
    log["id"] = ++this._logCount;
    log["msg"] = msg;
    this._logs.add(log);
  }
}
Exit mobile version