angularjs component


Component

https://docs.angularjs.org/guide/component
component本質上就是directive。

This is a shorthand for registering a special type of directive, which represents a self-contained UI component in your application. Such components are always isolated (i.e. scope: {}) and are always restricted to elements (i.e. restrict: 'E').
Component definitions are very simple and do not require as much configuration as defining general directives. Component definitions usually consist only of a template and a controller backing it.

MVC的本質就是將controller和template關聯起來,controller將數據顯示到template中。component將這種關聯做的更好。

When not to use Components:

  1. for directives that need to perform actions in compile and pre-link functions, because they aren't available
  2. when you need advanced directive definition options like priority, terminal, multi-element
  3. when you want a directive that is triggered by an attribute or CSS class, rather than an element

component解決了什么問題:

  1. app中的某個部分如何重用
  2. app中各部分之間的scope不是隔離的
  3. component可以自由的重復使用
  4. index.html被簡化了,細節的實現都分離出來了,提高了可維護性
  5. component是隔離的,不受外界影響,同時也不會影響app中的其他部分
  6. 可以獨立的測試我們的component

Comparison between Directive definition and Component definition

component使用

  1. 文件名建議:xxxComponent.component.js
  2. component名字規則和directive一樣,定義的時候使用駝峰樣式(myAwesomeComponent),模板中使用的時候使用-分割(my-awesome-component)
  3. template中使用controller的實例$ctrl替代scope來訪問數據,這個實例別名可以自定義 - 使用controllerAs屬性
  4. controller可以使用controller()注冊的controller,也可以使用行內定義的方式
<html ng-app="phonecatApp">
<head>
  ...
  <script src="bower_components/angular/angular.js"></script>
  <script src="app.js"></script>
  <script src="phone-list.component.js"></script>
</head>
<body>

  <!-- Use a custom component to render a list of phones -->
  <phone-list></phone-list>

</body>
</html>
// Define the `phonecatApp` module
angular.module('phonecatApp', []);

// Register `phoneList` component, along with its associated controller and template
angular.
  module('phonecatApp').
  component('phoneList', {
    template:
        '<ul>' +
          '<li ng-repeat="phone in $ctrl.phones">' +
            '<span>{{phone.name}}</span>' +
            '<p>{{phone.snippet}}</p>' +
          '</li>' +
        '</ul>',
    controller: function PhoneListController() {
      this.phones = [
        {
          name: 'Nexus S',
          snippet: 'Fast just got faster with Nexus S.'
        }, {
          name: 'Motorola XOOM™ with Wi-Fi',
          snippet: 'The Next, Next Generation tablet.'
        }, {
          name: 'MOTOROLA XOOM™',
          snippet: 'The Next, Next Generation tablet.'
        }
      ];
    },
   controllerAs: 'ctrl'
  });

example

var myMod = angular.module(...);
myMod.component('myComp', {
  template: '<div>My name is {{$ctrl.name}}</div>',
  controller: function() {
    this.name = 'shahar';
  }
});

myMod.component('myComp', {
  template: '<div>My name is {{$ctrl.name}}</div>',
  bindings: {name: '@'}
});

myMod.component('myComp', {
  templateUrl: 'views/my-comp.html',
  controller: 'MyCtrl',
  controllerAs: 'ctrl',
  bindings: {name: '@'}
});

API

component(name, options) returns ng.$compileProvider
https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object

bindings

這個就是類似於directive中的scope屬性, 支持:

  1. @ 字符值 - input
  2. < 單向綁定 - input
  3. & 回調傳遞 - 父組件的方法,用於向上的交互 - output
  4. = 雙向綁定 - 設計原則中不推薦使用
angular.module('docsIsolateScopeDirective', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
  $scope.igor = { name: 'Igor', address: '123 Somewhere' };
}])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerInfo: '=info'
    },
    templateUrl: 'my-customer-iso.html'
  };
});
    .component('qqtrMenu',{
        templateUrl:'/secu/components/menu/menu.component.html',
        bindings: {
            menuitems: "<"
        },
        controller: 'menuCompCtrl',
    })

交互式組件實例

https://plnkr.co/edit/?p=preview
index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-component-tabs-pane-production</title>
  

  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="script.js"></script>
  

  
</head>
<body ng-app="docsTabsExample">
  <my-tabs>
  <my-pane title="Hello">
    <h4>Hello</h4>
    <p>Lorem ipsum dolor sit amet</p>
  </my-pane>
  <my-pane title="World">
    <h4>World</h4>
    <em>Mauris elementum elementum enim at suscipit.</em>
    <p><a href ng-click="i = i + 1">counter: {{i || 0}}</a></p>
  </my-pane>
</my-tabs>
</body>
</html>

<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

script.js

(function(angular) {
  'use strict';
angular.module('docsTabsExample', [])
  .component('myTabs', {
    transclude: true,
    controller: function MyTabsController() {
      var panes = this.panes = [];
      this.select = function(pane) {
        angular.forEach(panes, function(pane) {
          pane.selected = false;
        });
        pane.selected = true;
      };
      this.addPane = function(pane) {
        if (panes.length === 0) {
          this.select(pane);
        }
        panes.push(pane);
      };
    },
    templateUrl: 'my-tabs.html'
  })
  .component('myPane', {
    transclude: true,
    require: {
      tabsCtrl: '^myTabs'
    },
    bindings: {
      title: '@'
    },
    controller: function() {
      this.$onInit = function() {
        this.tabsCtrl.addPane(this);
        console.log(this);
      };
    },
    templateUrl: 'my-pane.html'
  });
})(window.angular);

/*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

my-pane.html

<div class="tab-pane" ng-show="$ctrl.selected" ng-transclude></div>

<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

my-tabs.html

<div class="tabbable">
  <ul class="nav nav-tabs">
    <li ng-repeat="pane in $ctrl.panes" ng-class="{active:pane.selected}">
      <a href="" ng-click="$ctrl.select(pane)">{{pane.title}}</a>
    </li>
  </ul>
  <div class="tab-content" ng-transclude></div>
</div>

<!-- 
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->

基於組件的開發

https://docs.angularjs.org/guide/component
一個應用應該是一個組件數,每個組件只控制自己的視圖和數據. bindings只用字符和單向綁定,數據單向流入; 使用&綁定父組件的方法,實現向上交互

推薦和參考:

https://docs.angularjs.org/tutorial/step_03
https://docs.angularjs.org/api/ng/provider/$compileProvider#component
In order to retrieve and instantiate a component's controller, AngularJS provides the $componentController service.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM