我正在尝试访问应用程序 Controller 中定义的范围变量,以便我可以更新我创建的指令中的点击事件,但它似乎无法从其独立范围访问全局范围.
作用域变量已定义(currentTitle):
app.controller('news', function($scope, $http, $timeout) {
$scope.promise = $timeout(function() { //This is here just to mock the asynchronous loading of the data
$scope.articles = [{
title: 'Article 1',
content: 'It works!'
}, {
title: 'Article 2',
content: 'It still works'
}]
}, 3000);
$scope.currentTitle = "my - title";
$scope.showDetails = false;
});
指令中定义的范围是:
scope: {
//bind the showDetails into the scope so it can be seen by all of the accordion elements
promise: '&?',
currentTitle: '=?',
showDetails: '=?bind'
}
这是一个包含所有代码的codePen:http://codepen.io/valecarlos/pen/bpmryw
我想要做的是更新标题标题,当其中一个标题被点击时,现在我只是试图硬编码范围的 currentTitle
变量和 $apply
-在指令的点击事件中-,但我没有看到它反射(reflect)在 header 的标题上。
谢谢!
最佳答案
尝试将指令范围内的 currentTitle
键设置为此。它将创建一个双向绑定(bind),允许您从指令的范围内轻松更改父 Controller 中的 currentTitle
。
JS
scope: {
...
currentTitle: '=',
...
},
HTML
<accordion promise="promise" current-title="currentTitle">
<!--<dt ng-repeat-start="article in articles" ng-class="showDetails ? 'show-titles' : 'show-titles-not'">.-->
<dt ng-repeat-start="article in articles" ng-class="{'show-titles' : showDetails}">
<div class="grid-30">
<div class="round-div"></div>
</div>
<div class="grid-70">
<h5>{{article.title}}</h5>
</div>
</dt>
<dd ng-repeat-end="" ng-class="{'show-titles' : showDetails}">
<div class="grid-40">
<img src={{article.image}} alt="">
</div>
<div class="grid-60">
<div class="news-desc">
<h5>
{{article.title}}
</h5>
<p>
{{article.content}}
</p>
</div>
</div>
</dd>
</accordion>
关于javascript - 从指令访问 AngularJS 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921398/