大家。我是angularJS的新手,现在我正在尝试实现一些巡视。这是下面的代码。
问题是:如何访问回调onFinish(),并将其传递给组件“ my-timer”并运行? 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
答案 0 :(得分:0)
this.$onInit = function() {
this.countDown();
};
this.onFinish('1');
这里的问题是您试图在控制器体内直接执行this.onFinish
。那不会那样工作。如果要在初始化期间调用此函数,请将其移至$onInit
this.$onInit = function() {
this.countDown();
this.onFinish('1');
};
否则,从另一个组件方法调用它。您只能在控制器主体中声明变量和组件方法,而不能调用函数。