![](/img/trans.png)
[英]A validation directive that reacts to another value works in 1.0.x but not in 1.2.x
[英]AngularJS Scope differences between 1.0.x and 1.2.x
在下一個穩定的AngularJS發布時,我正在將我的應用程序從1.0.8遷移到1.2 。
在AngularJS 1.0.8中 ,可以為諸如follow
指令設置一個獨立的范圍。 然后該指令將使用自己的test()
函數而不是控制器的test()
函數。
<my-dialog property="something">
<button ng-click="test()">Load Test</button>
Check out the test: "{{ testMessage }}"
</my-dialog>
.controller('Ctrl', function(scope) {
scope.test = function () {
scope.testMessage = 'CTRL Test loaded! Whooops.';
}
})
.directive('myDialog', function() {
return {
restrict: 'E',
scope: {
property: '='
},
link: function(scope) {
scope.test = function () {
scope.testMessage = 'Isolated Test loaded. Yes!';
}
}
};
在AngularJS 1.2中,此行為不再起作用。 單擊該按鈕可立即觸發控制器的test()
函數。
看到這個jsFiddle比較:
究竟有什么變化,我如何重現舊的行為?
我發現我可以將指令模板放在一個額外的HTML文件中,或者將其編譯成一個字符串以使其正常工作( jsFiddle )但在我的情況下似乎太多了,因為模板已修復並將HTML拆分為幾個部分HTML文件很麻煩。
當沒有其他屬性可供分享時, @ elclanr的答案正常。 我更新了jsFiddle以傳遞一些任意屬性。 我現在該怎么辦?
看起來這是破壞性變化的預期結果: github.com/angular/angular.js/commit / ...在1.2.0(在rc3之后)中提取( https://github.com/angular/angular。 js / blob / master / CHANGELOG.md - 看看1.2.0的第一個重大變化 - $ compile):
修復了隔離范圍泄漏到同一元素上的其他指令的問題。
隔離范圍現在僅可用於請求它的isolate指令及其模板。
非隔離指令不應該在同一元素上獲取isolate偽指令的isolate范圍,而是接收原始范圍(它是新創建的隔離范圍的父范圍)。
另請參閱此討論: github.com/angular/angular.js/issues/4889
值得注意的是:“隔離范圍僅適用於模板,但不適用於指令未提供的標記。在1.2隔離范圍之前有一個導致此類泄漏的錯誤。 隔離范圍的要點是它僅適用到聲明它的指令,而不是其他指令或標記。 “(來自tbosch)
在1.2.0之前,同一DOM元素上的所有內容共享相同的范圍。 因此,1.2.0對使用隔離范圍的指令的工作方式進行了實質性的改變。
設定scope: true
應解決問題。 http://jsfiddle.net/rug3J/1 。 我還建議遵循約定並將其命名為scope
而不是$scope
,而不是依賴注入:
.directive('myDialog', function() {
return {
restrict: 'E',
scope: true,
link: function(scope) {
scope.test = function () {
scope.testMessage = 'Isolated Test loaded. Yes!';
}
}
};
為了將正常標記與指令特定模板和函數結合起來,需要使用transclude選項,如下所示:
見: jsFiddle
HTML
<div ng-app="myApp">
<div ng-controller="Ctrl">
<my-directive property="{{ something }}">
<p>{{ text }}</p>
</my-directive>
</div>
</div>
使用Javascript
.controller('Ctrl', ['$scope', function($scope) {
$scope.text = 'This is a controllers text.';
$scope.something = 'This is another controllers text.';
}])
.directive('myDirective', function() {
return {
restrict: 'E',
transclude: true,
template: '<button ng-click="test()">Fire directives function</button><div ng-transclude></div><p>{{ property }}</p>',
scope: {
property: '@'
},
link: function(scope) {
scope.test = function () {
scope.property = 'Loaded directives text.';
}
}
};
});
這對我來說現在很好用,但應該注意的是,不能覆蓋范圍的現有屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.