2025年10月29日 星期三

AngularJS - Component 使用紀錄

紀錄一下 AngularJs 的 Component 使用方法

HTML :
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>

<div ng-app="app" ng-controller="controller as ctrl">
  <attach-uploader some-variable="ctrl.parentvariable"
                   some-event="ctrl.parentFunction(text1, text2)">
  </attach-uploader>
</div>
JS :
var app = angular.module("app", []);
app.controller("controller", [function() {
   var self = this;
   this.parentvariable = "xxx";
   this.parentFunction = function(someText1, someText2) {
      console.log(someText1);
      console.log(someText2);
   }
}]);
app.component("attachUploader", {
  template: `<div>
	        <div ng-repeat="uploader in $ctrl.uploaderList track by $index">
                   <input type="file"
                          ng-attr-name="attachFile_{{$index}}"
                          file-validator="fileType:'png';"
                          /> 
                   <button ng-click="$ctrl.addUploader()">+</button>
                </div>
                <button ng-click="$ctrl.onXxxEvent('aaa', 'bbb')">Test button</button>
	      </div>`,
  bindings: {
     someVariable: "=",
     someEvent: "&" // function 的綁定
  },
  controller: function () {
    var self = this

    self.maxUploader = 5
    self.uploaderList = [{}]
    
    console.log('Test1: ' + self.someVariable); //會是 undefined
    self.$onInit = function() {
       console.log('Test1: ' + self.someVariable); //會是 xxx,要在 $onInit() 裡才會得到值
	}
    
    self.onXxxEvent = function(text1, text2) {
       self.someEvent({text1: text1, text2: text2}); //傳遞含有參數資訊的 Map 給 parent 的 function
    }

    self.addUploader = function () {
      if (self.uploaderList.length >= self.maxUploader) {
        return
      }
      self.uploaderList.push({})
    }
  },
});

沒有留言 :

張貼留言