Инструменты пользователя

Инструменты сайта


angular:angularjs:custom_directive:component

Различия

Здесь показаны различия между двумя версиями данной страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
angular:angularjs:custom_directive:component [2021/07/12 23:25]
werwolf
angular:angularjs:custom_directive:component [2023/01/12 12:18] (текущий)
Строка 125: Строка 125:
 </​code>​ </​code>​
  
-Итак, что у нас получилось с контроллером для обоих случаев:​+Итак, что у нас получилось с контроллером для обоих случаев:​\\ 
 +\\ 
 +**до** 
 +<code javascript>​
  
-<code javascript+<!DOCTYPE html
-// до +<html ng-app="​app">​ 
-.directive('​counter',​ function counter() { +<​head>​ 
-  ​return { +    <​title></​title>​ 
-    ​scope{}, +    ​<script src="​http://​crm.localhost/​vendor/​angular/​angular.min.js"></​script>​ 
-    ​bindToController:​ { +    ​<link href="​../​bootstrap-theme.css"​ rel="​stylesheet"​ /> 
-      count: '=' +    ​<link href="​../​bootstrap.css"​ rel="​stylesheet"​ /> 
-    ​}, +    ​<​script>​ 
-    ​controller: function () { +        ​angular.module("​app",​ []
-      ​function increment() { +        .controller("​studyCtrl", ​function ($scope) { 
-        ​this.count++; +            ​$scope.count = 5
-      } +        })
-      ​function ​decrement() { +
-        this.count--; +
-      } +
-      this.increment ​increment;​ +
-      this.decrement = decrement;​ +
-    }, +
-    controllerAs:​ '​counter'​ +
-  }+
-});+
    
-// после +        .directive('​counter',​ function counter() { 
-.component('​counter',​ { +            return { 
-  bindings: { +                scope: {}, 
-    count: '​='​ +                bindToController:​ { 
-  }, +                    count: '​='​ 
-  controller: function () { +                }, 
-    function increment() { +                controller: function () { 
-      this.count++;​ +  
-    +                    function increment() { 
-    function decrement() { +                        this.count++;​ 
-      this.count--;​ +                    } 
-    +                    function decrement() { 
-    this.increment = increment;​ +                        this.count--;​ 
-    this.decrement = decrement;​ +                    } 
-  +                    this.increment = increment;​ 
-});+                    this.decrement = decrement;​ 
 +                }, 
 +                controllerAs:​ '​counter',​ 
 +                template: [ 
 +                    '<​div class="​form-group">',​ 
 +                        '<​label class="​control-label col-md-1"​ for="">​Директива<​/label>',​ 
 +                        '<​div class="​input-group col-md-2">',​ 
 +                            '<​div class="​input-group-addon"​ ng-click="​counter.decrement();">​-<​/div>',​ 
 +                            '<​input class="​form-control"​ type="​text"​ ng-model="​counter.count">',​ 
 +                            '<​div class="​input-group-addon"​ ng-click="​counter.increment();">​+</​div>',​ 
 +                        '</​div>',​ 
 +                    '</​div>'​ 
 +                ].join(''​) 
 +            }; 
 +        }); 
 +  
 +    </​script>​ 
 +</​head>​ 
 +<body ng-controller="​studyCtrl as vm">​ 
 +    <div class="​container">​ 
 +        <​br>​ 
 +        <div class="​row">​ 
 +            <div class="​col-md-1"><​b>​контроллер</​b></​div>​ <div class="​col-md-2">​{{count}}</​div>​ 
 +        </​div>​ 
 +        <​br>​ 
 +        <div class="​row">​ 
 +            <​label><​counter ​ count="​count"></​counter></​label>​ 
 +        </​div>​ 
 +    </​div>​ 
 +</​body>​ 
 +</​html>​ 
 +</​code>​ 
 + 
 +**после**  
 +<code javascript>​ 
 +<​!DOCTYPE html> 
 +<html ng-app="​app">​ 
 +<​head>​ 
 +    <​title></​title>​ 
 +    <script src="​http://​crm.localhost/​vendor/​angular/​angular.min.js"></​script>​ 
 +    <link href="​../​bootstrap-theme.css"​ rel="​stylesheet"​ /> 
 +    <link href="​../​bootstrap.css"​ rel="​stylesheet"​ /> 
 +    <​script>​ 
 +        angular.module("​app",​ []) 
 +        .controller("​studyCtrl",​ function ($scope) { 
 +            $scope.count = 5; 
 +        }) 
 + 
 +        .component('​counter', ​ 
 +                bindings: { 
 +                    count: '​='​ 
 +                }, 
 +                controller: function () { 
 + 
 +                    ​function increment() { 
 +                        this.count++;​ 
 +                    
 +                    function decrement() { 
 +                        this.count--;​ 
 +                    
 +                    this.increment = increment;​ 
 +                    this.decrement = decrement;​ 
 +                }, 
 +                ​template:​ function($element,​ $attrs){ 
 +                    return [ 
 +                        '<​div class="​form-group">',​ 
 +                        '<​label class="​control-label col-md-1"​ for="">​Директива</​label>',​ 
 +                        '<​div class="​input-group col-md-2">',​ 
 +                        '<​div class="​input-group-addon"​ ng-click="​$ctrl.decrement()">​-</​div>',​ 
 +                        '<​input class="​form-control"​ type="​text"​ ng-model="​$ctrl.count">',​ 
 +                        '<​div class="​input-group-addon"​ ng-click="​$ctrl.increment()">​+</​div>',​ 
 +                        '</​div>',​ 
 +                        '</​div>'​ 
 +                    ].join(''​) 
 +                } 
 +        ​}); 
 + 
 +    </​script>​ 
 +</​head>​ 
 +<body ng-controller="​studyCtrl as vm">​ 
 +    <div class="​container">​ 
 +        <​br>​ 
 +        <div class="​row">​ 
 +            <div class="​col-md-1"><​b>​контроллер</​b></​div>​ <div class="​col-md-2">​{{count}}</​div>​ 
 +        </​div>​ 
 +        <​br>​ 
 +        <div class="​row">​ 
 +            <​label><​counter ​ count="​count"></​counter></​label>​ 
 +        </​div>​ 
 +    </​div>​ 
 +</​body>​ 
 +</​html>​
 </​code>​ </​code>​
  
Строка 216: Строка 301:
   ...   ...
 } }
 +</​code>​
 если мы задали свойство oneWay таким образом,​ то оно будет реагировать на изменения внешнего связанного объекта,​ при этом свои изменения передавать “наружу” не будет. И да, сразу отвечу на вопрос,​ который у вас наверное появился:​ работает только в одну сторону. если мы задали свойство oneWay таким образом,​ то оно будет реагировать на изменения внешнего связанного объекта,​ при этом свои изменения передавать “наружу” не будет. И да, сразу отвечу на вопрос,​ который у вас наверное появился:​ работает только в одну сторону.
  
Строка 222: Строка 308:
 Если вы посмотрите на исходный код, то увидите что разработчики AngularJS особо не парились и сделали метод **component()** просто оболочкой над directive(). Если вы посмотрите на исходный код, то увидите что разработчики AngularJS особо не парились и сделали метод **component()** просто оболочкой над directive().
  
-====Обновляемся до Angular2==== 
  
-Как уже было сказано:​ использование метода **.component()** серьезно упростит переход на **Angular2**. Посмотрите как будет выглядеть ваш компонент во второй версии фреймворка(конечно,​ с новым синтаксисом шаблонов):​\\ +
-<code javascript>​ +
-var Counter = ng +
-.Component({ +
-  selector: '​counter',​ +
-  template: [ +
-    ' +
-<div class="​todo">',​ +
-      '<​input type="​text"​ [(ng-model)]="​count">',​ +
-      '<​button type="​button"​ (click)="​decrement();">​-</​button>',​ +
-      '<​button type="​button"​ (click)="​increment();">​+</​button>',​ +
-    '</​div>​ +
-+
-  ].join(''​) +
-}) +
-.Class({ +
-  constructor:​ function () { +
-    this.count = 0; +
-  }, +
-  increment: function () { +
-    this.count++;​ +
-  }, +
-  decrement: function () { +
-    this.count--;​ +
-  } +
-}); +
-</​code>​ +
-</​code>​+
angular/angularjs/custom_directive/component.1626121506.txt.gz · Последние изменения: 2023/01/12 12:15 (внешнее изменение)