[英]Is the scope in an Angular directive link function the same $scope in an angular directive controller?
使用Javascript:
angular
.module('app', [])
.directive('compileExample', compileExample);
function compileExample() {
return {
restrict: 'E',
scope: {},
compile: function(tElement, tAttrs) {
angular.element(tElement).append("My name is {{name}}");
},
controller: function($scope, $element) {
$scope.name = "Liam";
},
}
}
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>controllerVsLink</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="main.js"></script>
</head>
<body ng-app="app">
<compile-Example></compile-Example>
</body>
</html>
這按我期望的方式工作,首先運行編譯,然后將該模板附加到元素,然后控制器將名稱更改為Liam,因此視圖顯示“我的名字是Liam”。 通過閱讀Angular docs鏈接,該鏈接也會在編譯后運行,所以當我將控制器更改為鏈接函數名稱時,為什么它永遠不會更新或顯示在視圖中,為什么會這樣?
angular
.module('app', [])
.directive('compileExample', compileExample);
function compileExample() {
return {
restrict: 'E',
scope: {},
compile: function(tElement, tAttrs) {
angular.element(tElement).append("My name is {{name}}");
},
link: function(scope, element) {
scope.name = "Liam";
},
}
}
指令鏈接功能和指令控制器功能之間的重要區別是參數的提供方式。
控制器函數參數按名稱注入 。
//This will work
controller: function($element, $scope) {
$scope.name = "Liam";
},
//AND this will work
controller: function($http, $scope, $element) {
$scope.name = "Liam";
},
控制器函數參數由$injector
服務提供,包括所有AngularJS服務以及本地用戶$scope
, $element
, $attrs
和$transclude
。
鏈接函數參數由position提供 。
//This will work
link: function(scope, element) {
scope.name = "Liam";
},
//This will FAIL
link: function(element, scope) {
scope.name = "Liam";
},
$compile
服務按位置提供鏈接函數參數,並且參數使用的名稱的行為與JavaScript中通常使用的函數參數相同。
有關注入的本地 變量的更多信息,請參見AngularJS $ compile Service API Reference-controller 。
有關按名稱進行注入的更多信息,請參見此堆棧溢出答案 。
看起來,如果您在指令定義對象中進行了編譯,它將禁用您在編譯外部指定的任何默認后鏈接函數。如果直接從編譯器返回鏈接,則該鏈接僅對編譯有效。經驗可以闡述
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.