AngularJs显示当前时间

来源:互联网 发布:win10不信任软件 编辑:程序博客网 时间:2024/05/16 14:24
testdrective3.html
<span style="font-size:14px;"><!DOCTYPE html><html ng-app="time">  <head>    <script src="../js/angular.js"></script>    <script src="directive3.js"></script>  </head>  <body>  <!-- 显示当前时间 -->    <div ng-controller="Ctrl2">      Date format: <input ng-model="format"> <hr/>      Current time is: <span my-current-time="format"></span>    </div>  </body></html></span>
directive3.js
<span style="font-size:14px;">var time = angular.module('time', [])  // Register the 'myCurrentTime' directive factory method.  // We inject $timeout and dateFilter service since the factory method is DI.  .directive('myCurrentTime', function($timeout, dateFilter) {    // return the directive link function. (compile function not needed)    return function(scope, element, attrs) {      var format,  // date format          timeoutId; // timeoutId, so that we can cancel the time updates      // used to update the UI      function updateTime() {        element.text(dateFilter(new Date(), format));      }      // watch the expression, and update the UI on change.      scope.$watch(attrs.myCurrentTime, function(value) {        format = value;        updateTime();      });      // schedule update in one second      function updateLater() {        // save the timeoutId for canceling        timeoutId = $timeout(function() {          updateTime(); // update DOM          updateLater(); // schedule another update        }, 1000);      }      // listen on DOM destroy (removal) event, and cancel the next UI update      // to prevent updating time ofter the DOM element was removed.      element.bind('$destroy', function() {        $timeout.cancel(timeoutId);      });      updateLater(); // kick off the UI update process.    }  });time.controller('Ctrl2',function($scope){$scope.format = 'yyyy-MM-dd h:mm:ss';});</span>


0 0
原创粉丝点击