我试图访问app控制器中定义的范围变量,这样我就可以更新来自我创建的Directive的点击事件,但它似乎无法访问全球范围来自其孤立的范围。
定义范围变量(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
- 在指令中的点击事件中,但我没有看到它反映在标题的标题上。
谢谢!
答案 0 :(得分:2)
尝试在指令范围内设置currentTitle
密钥。它将创建一个双向绑定,允许您从指令的范围轻松更改父控制器中的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>
答案 1 :(得分:1)
如果您使用“&amp;”传递函数语法,您应该能够在指令中调用它。
让我们假设控制器中的函数如下所示:
$scope.someFunction = function(someParameter) {...}
然后您的指令将如下所示:
... scope { someFunction: "&" } ... //in link or controller $scope.someFunction({someParameter:'foo'});