[英]How to pass values to template in angular directive?
I have found this code for a countdown timer and tweaked it a little. 我已经找到了倒计时计时器的代码,并对其进行了一些调整。
angular.module('app').directive('countdown', [
'Util', '$interval', function (Util, $interval) {
return {
restrict: 'A',
scope: {
date: '@'
},
link: function (scope, element) {
var future;
future = new Date(scope.date);
$interval(function () {
var diff;
diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
var d = Util.dhms(diff);
var el = "<div class='time_division_container'><div class='digits_container'>"+d[0]+"</div><div class='label_container'>DAYS</div></div><div class='time_division_container'><div class='digits_container'>"+d[1]+"</div><div class='label_container'>HOURS</div></div><div class='time_division_container'><div class='digits_container'>"+d[2]+"</div><div class='label_container'>MINUTES</div></div><div class='time_division_container'><div class='digits_container'>"+d[3]+"</div><div class='label_container'>SECONDS</div></div>";
return element.replaceWith(el);
}, 1000);
}
};
}
]).factory('Util', [
function () {
return {
dhms: function (t) {
var days, hours, minutes, seconds;
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
return [days, hours, minutes, seconds];
}
};
}
]);
Basically all I wanted to happen is to put the days, hours, minutes and seconds in this template: 基本上我想做的就是在此模板中放入天,小时,分钟和秒:
<div class='time_division_container'>
<div class='digits_container'>{{ days }}</div>
<div class='label_container'>DAYS</div>
</div>
<div class='time_division_container'>
<div class='digits_container'>{{ hours }}</div>
<div class='label_container'>HOURS</div>
</div>
<div class='time_division_container'>
<div class='digits_container'>{{ minutes }}</div>
<div class='label_container'>MINUTES</div>
</div>
<div class='time_division_container'>
<div class='digits_container'>{{ seconds }}</div>
<div class='label_container'>SECONDS</div>
</div>
Using the directive I placed it like this: 使用指令,我将其放置如下:
<div countdown='' date='January 1, 2018 12:00:00'> </div>
It was displaying the template but the timer is not moving. 它正在显示模板,但计时器未移动。 What could be causing this? 是什么原因造成的? Please help. 请帮忙。 Thanks. 谢谢。
Alright, I know I am new to angular. 好吧,我知道我是新手。 Just found out by trying 只是通过尝试发现了
return element.html(el);
instead of 代替
return element.replaceWith(el);
and now it works. 现在可以了。
@
is for a one-way databinding. @
是单向数据绑定。 This means that if you change your value in your controller/directive, the view won't be updated. 这意味着,如果您更改控制器/指令中的值,则不会更新视图。
Use =
for a two-way databinding and reflect changes on view. 使用=
进行双向数据绑定,并在视图上反映更改。
scope: {
date: '='
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.