scope.$watch
당신이 기대하는 바를 잘 모르겠습니다. scope.$watch
은 첫 번째 인수로 현재 범위에서 평가할 식을 취합니다. 이 표현식이 새로운 값을 반환하면 새로운 값을 가진 두 번째 인자 인 함수를 호출합니다. 따라서,
scope.$watch('ready', function() {...});
는 기본적으로
호출이 기능마다 scope.ready
변화를 말과 동일합니다.
이것은 분명히 원하는 것이 아닙니다.
기능상으로 - 다음과 같이 구현할 수있는 몇 가지 방법이 있습니다. 이 경우
app.filter('timeago', function() {
return function(time) {
if(time) return jQuery.timeago(time);
else return "";
};
});
<p>The timestapm was {{conversation.timestamp|timeago}} ago.</p>
은, 그러나, 반환 된 문자열이 자동으로 다이제스트주기 범위에서 실행 될 때마다 새로 고침 것 : 첫 번째는 간단한 필터입니다.
이
에만 정확히 한 번만 타임 스탬프를 처리하려면 다음과 같은 지침을 사용할 수 있습니다 :
app.directive('timeago', function($timeout) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
scope.$watch(attrs.timeago, function(value) {
if(value) elem.text(jQuery.timeago(value));
});
}
};
});
여기
<p>The timestamp was <span timeago="conversation.timestamp"></span> ago.</p>
이 버전 다이제스트주기 15 초마다 자동으로 업데이트하기를 다시 실행 모든 너무 자주 타임 스탬프 :
app.directive('timeago', function($timeout) {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
var updateTime = function() {
if (attrs.timeagoAutoupdate) {
var time = scope.$eval(attrs.timeagoAutoupdate);
elem.text(jQuery.timeago(time));
$timeout(updateTime, 15000);
}
};
scope.$watch(attrs.timeago, updateTime);
}
};
});
<p>The timestamp was <span timeago="conversation.timestamp"></span> ago.</p>
Here is a jsFiddle 모든 t을 보여줍니다 hree 예제. 두 번째 예제 (timeagoAutoupdate
지시문)가 scope.$eval
을 호출하기 때문에 필터가있는 세 번째 예제가 자동으로 매분마다 업데이트된다는 유일한 이유가 있습니다.
http://stackoverflow.com/questions/13526584/angularjs-ngrepeat-and-directive/13528336#13528336을 참조하십시오. scope 대신에 attrs. $ observe를 사용할 필요가 있습니다. – abhaga