angular directive 深入理解

由于业务的需要,最近angular 的diretive 研究的比较多,有和同事一起共同协作开发scada的项目, 对directive 有了进一步更深的理解。

感觉才开始真正理解了这句话的意思:

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied

这句话,感觉道出了diretive的原理的精髓。

--------------------------------------------------------------------------------------------------------------------

> is not in the documentation.

< is for one-way binding.

@ binding is for passing strings. These strings support {{}} expressions for interpolated values.

= binding is for two-way model binding. The model in parent scope is linked to the model in the directive‘s isolated scope.

& binding is for passing a method into your directive‘s scope so that it can be called within your directive.

When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.

---------------------------------------------------------------------------------------------------------------------

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.

This is illustrated best with an example:

<div my-customer name="Customer XYZ"></div>

and the directive definition:

angular.module(‘myModule‘, [])
.directive(‘myCustomer‘, function() {
  return {
    restrict: ‘E‘,
    scope: {
      customerName: ‘@name‘
    },
    controllerAs: ‘vm‘,
    bindToController: true,
    controller: [‘$http‘, function($http) {
      var vm = this;

      vm.doStuff = function(pane) {
        console.log(vm.customerName);
      };
    }],
    link: function(scope, element, attrs) {
      console.log(scope.customerName);
    }
  };
});

When the scope property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.

In very simple terms, the meaning of the binding symbols is:

someObject: ‘=‘ (two-way data binding)

someString: ‘@‘ (passed directly or through interpolation with double curly braces notation {{}})

someExpression: ‘&‘ (e.g. hideDialog())

This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.

The symbol > is not part of the syntax.

However, < does exist as part of the AngularJS component bindings and means one way binding.

<!DOCTYPE>
<html ng-app="App">
    <head>
        <meta charset="utf-8"/>
        <script src="./js/angular.min.js"></script>
        <script>
            var app = angular.module(‘App‘, []);
            app.controller(‘appCtrl‘, function($scope){
            	// $scope.names = {age: 12};
            	$scope.names = ‘FLY‘;
            	// DB.getAl().then(function (rsp) {
                 //    $scope.name=100;
	            // })
            	$scope.changeNames = function(){
            		$scope.names = "AAA";
                };
            	$scope.cbFun = function(name){
            		// alert(‘parent action.‘);
                    alert(name);
		            /**
                     *
                     *
                     *
		             */
	            };
            	$scope.doStuff = function () {
                    alert(‘parent scope‘);
	            }

            });
            app.directive(‘myCustomer‘, function(){
            	return {
            		scope: {
            			fly: ‘@‘
                    },
            		restrict: ‘A‘,
                    link: function(scope, element, attr){
            			console.log(‘attr: ‘, attr);

            			console.log("myCustomer: ", scope);
                    },
		            controllerAs: ‘vmst‘,
		            bindToController: true,
		            controller: [‘$scope‘, ‘$http‘, function(scope, $http) {
			            var vm = this;
                        console.log(‘this: ‘, this);
                        console.log(‘scope: ‘, scope);
			            vm.doStuff = function(pane) {
				            console.log(vm.customerName);
			            };
			            vm.name = ‘pxk‘;
			            scope.doStuff = function(){
			            	alert(‘asdfafa‘);
                        }
		            }],
                    // template: ‘<button ng-click="doStuff();">aaaa</button>‘
                };
            });

        </script>
    </head>
    <body ng-controller="appCtrl">
        <div my-customer="" haha="12ab3" fly="jiayou">myCustomer

            <button ng-click="doStuff();">aaa</button>
        </div>
        <hr/>
    </body>
</html>

  

原文地址:https://www.cnblogs.com/oxspirt/p/9242561.html

时间: 2024-10-09 00:58:19

angular directive 深入理解的相关文章

满脑子都是Angular/directive/scope/git

坑1: directive要用到controller里面的东西呢,有两种办法: 通过$scope.xxx来设置的,直接用xxx引用 通过controller function 里面的 this.xxx 设置的,要通过controllerName.xxx引用 爬爬墙,更健康:附AngularJS Directive文档 坑2: git rebase和git merge有啥不同? 看看这:rebase的用法 满脑子都是Angular/directive/scope/git

angular directive restrict 的用法

E 表示该指令是一个element; A 表示该指令是attribute; C 表示该指令是class; M 表示该指令是注视 实例如下: 原帖:www.thinkster.io/angularjs/rep5re7gTM/angularjs-directive-restrictions While it’s cool to make a custom element like we did the the previous cast, it’s actually more common to d

angular 自定义指令 directive transclude 理解

项目中断断续续的用了下angular,也没狠下心 认真的学习.angular 特别是自定义指令这块 空白. transclude 定义是否将当前元素的内容转移到模板中.看解释有点抽象. 看解释有点抽象Demo: <!DOCTYPE html> <html lang="en" ng-app='myApp'> <head> <meta charset="UTF-8"> <title>Angularjs</

angular Directive 指令详解

一.定义 指令,可以把它简单的理解成在特定DOM元素上运行的函数,指令可以扩展这个元素的功能. 指令的基本结构如下: angular.module('myApp', []) .directive('myDirective', function() { return { restrict: String, priority: Number, terminal: Boolean, template: String or Template Function: function(tElement, tA

Angular directive 实例详解

准备代码,会在实例中用到 var app = angular.module('app', []); angular指令定义大致如下 app.directive('directiveName', function() { return { // config } }) 其中return返回的配置对象包含很多参数,如下一一说明. 1. restrict 值为字符串,可选参数,指明指令在DOM中以什么形式被声明 <!-- E (element) --> <directiveName>&l

[Angular Directive] Create a Template Storage Service in Angular 2

You need to define a <template> to be able to use it elsewhere in your app as a TemplateRef. You can store these TemplateRefs in a Service and then access them from any @Directive or @Component in your app. We want to create a service and a componen

angular.directive

var m=angular.moduel("module",[]); m.directive("myDrag",function(){    //驼峰是写法 下面用 my-drag 你这里就得用myDrag return { restrict:"A",               // A代表属性 attr  , E代表元素 element, C 代表class ,M 代表注释 scope:{                   // 这个里面的

[Angular Directive] Implement Structural Directive Data Binding with Context in Angular

Just like in *ngFor, you're able to pass in data into your own structural directives. This is done by declaring the variable using a let statement then passing context into the createEmbeddedView call. We know *ngFor we did like this: *ngFor="let mes

[Angular Directive] Assign a Structual Directive a Dynamic Context in Angular 2

Just like passing in an array to *ngFor, you can pass in any value into your structural directive so that it can render templates based on those values. It's crucial to understand how the *directive syntax expands into a <template> and adds a custom