Vietnam

    Nodejs.vn

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Tags
    • Groups
    • Search

    Hỏi về directive trong angularjs

    Hỏi Đáp
    angularjs directive
    0
    4
    1180
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • P
      phatht last edited by

      Nhu cầu của mình là chuyển từ timestamp (milisecond Unix) sang chuỗi datetime, mình có thử tạo directive (để view có thể sử dụng nhiều nơi), cụ thể:

      Code html của mình như thế này:

      <input type="text" ng-model="text" />
      <span show-date="{{text}}"></span>
      

      Directive showDate của mình như thế này:

      angular.module('app').directive('showDate', function(){
      	return {
      		link: function(scope, element, attrs){
      			var timestamp = (attrs.showDate);
      			var d = new Date(+timestamp);
      			element.html(d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes());
      		}
      	}
      });
      

      Vấn đề là cái html Inner của span chỉ show kết quả ban đầu (1970/1/1 xx:yy), khi nhập giá trị mới cho {{text}} thì span vẫn giữ nguyên, không thay đổi gì cả (?!!)
      Vậy mình hiểu sai hay thiếu cái gì trong directive showDate của mình?

      blqthien Vũ 2 Replies Last reply Reply Quote 0
      • blqthien
        blqthien @phatht last edited by blqthien

        @phatht bạn có thể dùng filter.
        https://docs.angularjs.org/api/ng/filter/date

        1 Reply Last reply Reply Quote 0
        • Vũ
          Vũ Global Moderator @phatht last edited by

          @phatht Hàm link bạn đang sử dụng chỉ chạy 1 lần sau khi DOM được sinh ra. Bạn cần phải theo dõi attribute showDate bằng hàm $watch, sau đó, cập nhật lại view.

          Bạn tham khảo thêm ví dụ mẫu trên trang chủ của nó ở mục Creating a Directive that Manipulates the DOM

          • https://docs.angularjs.org/guide/directive
          • https://docs.angularjs.org/api/ng/service/$compile#-link-

          Tech-nông
          Email: [email protected]
          Profile: about.me/vunb
          Github: github.com/vunb
          Twitter: twitter.com/nhubaovu

          1 Reply Last reply Reply Quote 0
          • P
            phatht last edited by

            Thank all

            1 Reply Last reply Reply Quote 0
            • First post
              Last post