[英]How do I pass a variable from the parent scope to a child scope in AngularJS
我有一個部分頁面,其代碼類似於以下內容:
<div class="selector-result row">
<div ng-if="resultCtrl.result">
<div class="col-xs-12">
<h4><strong>We Recommend:</strong></h4>
<h2><strong>{{resultCtrl.result.Name}}</strong></h2>
</div>
<div class="row">
<div class="col-md-4">
<div ng-controller="selectorResultCarouselController">
<div>
<div style="height: 305px">
<carousel interval="myInterval" no-wrap="false">
<slide ng-repeat="slide in slides" active="slide.active" actual="slide">
<img ng-src="{{slide.image}}" style="margin:auto;">
</slide>
</carousel>
</div>
</div>
</div>
...
我有一個模塊,該模塊具有帶有controllerAs resultCtrl的指令(selectorResult)。 那里也有一個控制器,selectorResultController,它加載變量“結果”。
我想做的是以某種方式將{{resultCtrl.result.AllImages}}放入選擇器結果,以便將其添加到輪播中。 我迷路了。 我正在努力理解Angular,並且我想我了解各部分的工作原理,只是我不了解該系統,如果那是有道理的。
我只是在這里找些微動。 我已經閱讀並閱讀了,但是我還沒有看到任何能解決這個問題的東西。
為了避免$scope
混亂,請考慮使用AngularJS的controllerAs語法 。 基本上,不是將值附加到$scope
,而是將它們附加到控制器對象本身。 所以:
angular.module('myApp', [])
.controller('ctrlOne', [function() {
var self = this;
self.name = 'ctrlOne';
}])
.controller('ctrlTwo', [function() {
var self = this;
self.name = 'ctrlTwo';
}]);
和
<div ng-app="myApp">
<div ng-controller="ctrlOne as one">
<div ng-controller="ctrlTwo as two">
<p>{{one.name}}</p> <!-- 'ctrlOne' -->
<p>{{two.name}}</p> <!-- 'ctrlTwo' -->
</div>
</div>
</div>
子范圍繼承自父范圍。 因此,只需使用$ scope.result.AllImages。
“子作用域”(典型地)從其父作用域繼承屬性。
來自: https : //docs.angularjs.org/guide/scope 。
在您的情況下,在您的子范圍內,變量可以作為$scope.result.Allmages
。
如果您的指令具有隔離范圍,則必須通過指令定義對象(ddo)中的屬性將其綁定。 屬性&,@和=將允許您執行此操作。
scope { myAttribute: '@', myOtherAttribute: '&', myLastAttribute: '='}
在您的指令中,您將使用類似:
<my-directive my-attribute="someString" my-other-attribute="someCallbackOnControllerScope()" my-last-attribute="somePropertyOnControllerScopeYouWantToBindTwoWays">
請注意,如果使用“ @”,它將作為字符串傳遞,並且您必須針對父作用域進行解析以將其轉換為對象(在指令的后鏈接函數中):
$parse(myAttribute)(scope.$parent)
否則,您的ddo可以將scope屬性設置為false,在這種情況下,它將使用父范圍。
如果您在ddo中將scope屬性設置為true,您仍然可以解決父范圍屬性(通過引用它,就好像您沒有子范圍/好像已經在同一范圍內一樣),盡管這樣做要小心。 this(scope:true)並具有多個相同的指令...因為它們將共享相同的作用域,因此彼此覆蓋。
請查看此頁面以獲取更多信息: AngularJS文檔
我希望這可以幫到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.