AngularJS global scope and Isolate scope communication usage example
The example in this article describes the communication usage between AngularJS global scope and Isolate scope. Share it with everyone for your reference, the details are as follows:
During project development, the usage scope of global scope and directive local scope is not clear enough, and the communication between global scope and directive local scope is not thorough enough. Here is the use of global scope and directive local scope. conclude.
1. Scope
1. In AngularJS, child scopes generally inherit the properties and methods of their parent scope through the JavaScript prototype inheritance mechanism. But there is an exception: when using scope: { ... } in a directive, the scope created in this way is an independent "Isolate" scope. It also has a parent scope, but the parent scope is not on its prototype chain. There is no prototypal inheritance from the parent scope. Defining scopes in this way is usually used to construct reusable directive components.
2. If we access a property defined in the parent scope in the child scope, JavaScript first looks for the property in the child scope. If it is found, it will be searched from the parent scope on the prototype chain. If it is not found yet, it will be searched for in the parent scope of the upper prototype chain. In AngularJS, the top of the scope prototype chain is $rootScope, and JavaScript searches until $rootScope.
3. scope: { ... } - directive creates an independent "Isolate" scope without prototypal inheritance. This is the best option for creating reusable directive components. Because it does not directly access/modify the properties of the parent scope, it will not produce unexpected side effects.
2. Isolate scope reference modifier
1. = or =attr The attributes of the "Isolate" scope are two-way bound to the attributes of the parent scope. Modifications on either side will affect the other. This is the most commonly used method. ;
2. @ or @attr The attributes of the "Isolate" scope are one-way bound to the attributes of the parent scope, that is, the "Isolate" scope can only read the value of the parent scope, and the value is always a String Type;
3. & or &attr "Isolate" scope wraps the attributes of the parent scope into a function, thereby reading and writing the attributes of the parent scope in a functional way. The packaging method is $parse
3. Directive and controller Data transfer and communication
1. The parent controller listens to the global scope (parent scope) variable and broadcasts events to the child scope (directive scope, each directvie has its own independent scope)
2. The directive defines the local scope, Display references to the global scope through =, @, & (method) characters
3. Directive scope (subscope) references the properties of the global scope through parent[$scope.$parent.xxx]
4. Directive monitors global scope variable changes , you can use the $scope.$parent.$watch method
IV. Example description
<div ng-controller="MyCtrl"> <button ng-click="show=true">show</button> <dialog title="Hello }" visible="}" on-cancel="show=false;" on-ok="show=false;parentScope();"> <!--上面的on-cancel、on-ok,是在directive的isoloate scope中通过&引用的。 如果表达式中包含函数,那么需要将函数绑定在parent scope(当前是MyCtrl的scope)中--> Body goes here: username:} , title:}. <ul> <!--这里还可以这么玩~names是parent scope的--> <li ng-repeat="name in names">}</li> </ul> <div> Email:<input type="text" ng-model="email" style="width: 200px;height:20px"/> </div> <div> Count:<input type="text" ng-model="person.Count" style="width: 120px;height:20px"/> <button ng-click="changeCount()">Count加1</button> </div> <p></p> </dialog> </div>
Controller test code:
var app = angular.module("Dialog", []); app.controller("MyCtrl", function ($scope) { $scope.person = { Count: 0 }; $scope.email = 'carl@126.com'; $scope.names = ["name1", "name2", "name3"]; $scope.show = false; $scope.username = "carl"; $scope.title = "parent title"; $scope.parentScope = function () { alert("scope里面通过&定义的东东,是在父scope中定义"); }; $scope.changeCount = function () { $scope.person.Count = $scope.person.Count + 1; } // 监听controller count变更, 并发出事件广播,再directive 中 监听count CountStatusChange变更事件 $scope.$watch('person.Count', function (newVal, oldVal) { console.log('>>>parent Count change:' + $scope.person.Count); if (newVal != oldVal) { console.log('>>>parent $broadcast count change'); $scope.$broadcast('CountStatusChange', {"val": newVal}) } }); }); app.directive('dialog', function factory() { return { priority: 100, template: ['<div ng-show="visible">', ' <h3 id="">}</h3>', ' <div class="body" ng-transclude></div>', ' <div class="footer">', ' <button ng-click="onOk()">OK</button>', ' <button ng-click="onCancel()">Close</button>', ' </div>', '</div>'].join(""), replace: false, transclude: true, restrict: 'E', scope: { title: "@",//引用dialog标签title属性的值 visible: "@",//引用dialog标签visible属性的值 onOk: "&",//以wrapper function形式引用dialog标签的on-ok属性的内容 onCancel: "&"//以wrapper function形式引用dialog标签的on-cancel属性的内容 }, controller: ['$scope', '$attrs', function ($scope, $attrs) { // directive scope title 通过@ 引用dialog标签title属性的值,所以这里能取到值 console.log('>>>title:' + $scope.title); >>>title:Hello carl scope.html:85 // 通过$parent直接获取父scope变量页可以 console.log('>>>parent username:' + $scope.$parent.username); >>>parent username:carl // directive scope 没有定义username 变量,并且没有引用父scope username变量, 所以这里是undefined console.log('>>>child username:' + $scope.username); >>>username:undefined // 接收由父controller广播count变更事件 $scope.$on('CountStatusChange', function (event, args) { console.log("child scope on(监听) recieve count Change event :" + args.val); }); // watch 父 controller scope对象 $scope.$parent.$watch('person.Count', function (newVal, oldVal) { console.log('>>>>>>>child watch parent scope[Count]:' + oldVal + ' newVal:' + newVal); }); }] }; });

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools