使用AngularJS组件属性

pod7payv  于 2022-10-31  发布在  Angular
关注(0)|答案(1)|浏览(164)

我是angularJS的新手,现在我正在尝试实现一些部分。
提出的问题是:如何访问传递给组件“my-timer”的回调onFinish()并运行它?this.onFinish()返回错误。
以下是我的标记:

<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

kokeuurv

kokeuurv1#

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

this.onFinish('1');

这里的问题是你试图直接在控制器的主体中执行this.onFinish。但那是行不通的。如果你想在初始化时调用这个函数,把它移到$onInit

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

否则,从另一个组件方法调用它。您只能在控制器主体中声明变量和组件方法,但不能调用函数。

相关问题