This article will introduce to you the differences between scope in elem.scope(), elem.isolateScope and $compile(elem)(scope) in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
[Related recommendation: "angular tutorial"]
In the process of using angular, we often use $rootScope.$new () Create a new scope scope for elem, and then use $compile(elem)(scope) to compile the element containing the directive. So what is the scope of the scope passed in here? What is the scope of scope.$$childHead? What scope does the compiled elem.scope() return? What scope does elem.isolateScope() return? It is necessary to know this, especially when using jasmine to test angular instructions. Let's use an example to verify it.
index.html
<!DOCTYPE html> <html ng-app="myapp"> <head> <meta charset="utf-8"> <title>angular test</title> </head> <body ng-controller="myCtrl"> </body> <script src="./node_modules/angular/angular.js"></script> <script src="./index.js"></script> </html>
index.js
var app = angular.module('myapp',[]); app.controller('myCtrl', function($compile, $rootScope){ //创建一个新的作用域,并添加两个属性 var scope_0 = $rootScope.$new(); scope_0.color = "red"; scope_0.name = "Jhon"; //编译该指令并插入body中 var elem = angular.element('<p mcolor="{{color}}">你好吗?</p>'); $compile(elem)(scope_0); var body = document.querySelector('body'); angular.element(body).append(elem) //获取这几个作用域 var scope_1 = elem.scope(); var scope_2 = elem.isolateScope(); var scope_3 = scope_0.$$childHead; //并打印 console.log("scope_0:", scope_0); console.log("scope_1:", scope_1); console.log("scope_2:", scope_2); console.log("scope_3:", scope_3); }); app.directive('mcolor',function(){ return { restrict: 'A', scope:{ mcolor: '@' }, link: function(scope, elem, attrs){ elem.css('color', scope.mcolor); } } });
The result after execution is that the interface displays a red "How are you?", Of course this is not what we are concerned about. Let's take a look at the printed log:
scope_0: color:"red" name:"Jhon" scope_1: color:"red" name:"Jhon" scope_2: mcolor:"red" scope_3: mcolor:"red"
From this we can draw the following conclusions:
$compile(elem)(scope), the scope here is the peripheral scope of the instruction.
The scope returned by elem.scope() is the outer scope of the instruction.
elem.isolateScope() returns the independent scope of the instruction.
scope.$$childHead returns the independent scope of the directive.
For more programming-related knowledge, please visit: Programming Teaching! !
The above is the detailed content of A brief discussion on the differences between scopes in elem.scope(), elem.isolateScope and $compile(elem)(scope) in Angular. For more information, please follow other related articles on the PHP Chinese website!