【发布时间】:2014-10-29 14:34:57
【问题描述】:
我有一个TimelineController,在作用域上有一个publish 函数,它将向服务器发送一些数据。
我的时间线由2个directives组成
- 时间线(元素)
- 分享帖子(元素)
我希望能够从share-post 指令中调用我的TimelineController 上的publish 函数,这可能吗?
控制器
function TimelineController($scope,TimelineService)
{
$scope.posts = [];
$scope.publish = function(wall_type,wall_id,text,video,image) {
console.log('click controller');
TimelineService.publishPost(wall_type,wall_id,text,video,image).$promise.then(function(result){
$scope.posts.push(result.response);
});
};
}
时间线指令:
function timelineDirective() {
return {
restrict: 'E',
replace: true,
scope: {
type: '@',
ids: '@',
postime: '&',
posts: '='
},
templateUrl:"/js/templates/timeline/post-tmpl.html",
controller: function($scope,$element) {
this.type = $element.attr('type');
this.ids = $element.attr('ids');
}
}
};
时间线指令模板
<ol class="timeline" ng-init="postime({wall_type:type,wall_id:ids})">
<li>
<share-post></share-post>
</li>
<li ng-repeat="post in posts">
{{post.text}}
</li>
</ol>
SharePost 指令:我想通过这个指令调用 TimelineController 上的发布
function sharePost() {
return {
restrict: 'E',
replace: true,
require: "^timeline",
templateUrl:"/js/templates/timeline/share-tmpl.html",
link: function($scope,$element,$attr,ctrl) {
$scope.pub = function() {
// This does not work because it call the parent directive
// Instead of controller
$scope.publish(ctrl.type, ctrl.ids, $scope.text);
}
}
}
};
分享发布指令模板
<div class="module comment">
<div class="content">
<textarea class="form-control" ng-model="text" placeholder="What is going on..." rows="2"></textarea>
</div>
<button type="button" class="btn" ng-click="pub()"> Share</button>
</div>
【问题讨论】:
-
我认为您应该将 TimelineService 服务直接注入您的指令中,或者使用属性将“发布”功能注入您的指令范围
-
我想避免将服务注入指令
-
@Fabrizio,让我直说吧,你想从指令触发控制器上的点击事件吗?
-
@jack.the.ripper 我想从指令中的事件
click触发控制器中的函数$scope.publish。
标签: javascript angularjs angularjs-directive angularjs-scope