使用 AngularJS 个组件道具

Using AngularJS component props

各位。我是 angularJS 的新手,现在我正在努力认识一些朋友。下面是我的代码。

问题是:如何访问传递给组件 "my-timer" 和 运行 的回调 onFinish()? this.onFinish() returns 错误。

这是我的标记:

<div ng-app="app" ng-controller="MyCtrl as myCtrl">
  <div>
    Status: {{myCtrl.status ? myCtrl.status : 'Waiting...'}}
  </div>

  <div>
    <button ng-click="myCtrl.addTimer(5)">Add timer</button>
  </div>

  <div ng-repeat="timer in myCtrl.timers">
    <div>
      <h3>Timer {{timer.id}}</h3>
      <button ng-click="myCtrl.removeTimer($index)">X</button>
      <my-timer id="{{timer.id}}" start-seconds="{{timer.seconds}}" on-finish="myCtrl.onFinish(endTime)"></my-timer>
    </div>
  </div>
</div>

这里是index.js

var app = angular.module('app', []);

app.controller('MyCtrl', class {
      constructor($scope) {
        this.status = null;
        this.timerId = 0;
        this.timers = [];
        this.addTimer(10);
        this.addTimer(3);
      console.log($scope);
      }

  addTimer(seconds) {
    this.timers.push({
      id: this.timerId++,
      seconds
    });
  }

  removeTimer(index) {
    this.timers.splice(index, 1);
  }

onFinish(endTime){
    this.status = `Timer finished at ${endTime}`;
  console.log(endTime);
}

});

app.component('myTimer', {
  bindings: {
    id: '@',
    startSeconds: '@',
    onFinish: '&',
  },

  controller: function($interval, $scope) {
    this.endTime = null;

this.$onInit = function() {
  this.countDown();
};

this.countDown = function() {
  $interval(() => {
    this.startSeconds = ((this.startSeconds - 0.1) > 0) ? (this.startSeconds - 0.1).toFixed(2) : 0;
  }, 100);
}; 
  },
template: `<span>{{$ctrl.startSeconds}}</span>`,
});

这里是jsFiddle

this.$onInit = function() {
  this.countDown();
};

this.onFinish('1');

这里的问题是您试图在控制器主体中执行 this.onFinish。那不会那样工作。如果要在初始化时调用此函数,将其移动到$onInit

this.$onInit = function() {
  this.countDown();
  this.onFinish('1');
 };

否则,从另一个组件方法调用它。 controller body中只能声明变量和组件方法,不能调用函数