我有一個TimelineController
,它在作用域上有一個publish
函數,它將向服務器發送一些數據。從指令AngularJs觸發控制器範圍
我的時間表是由2 directives
- 時間表(元)
- 股份後(元素)組成
我希望能夠從指令的publish
調用功能在我的TimelineController
是可能的嗎?
控制器
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);
}
}
}
};
Sharepost指令模板
<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服務到你的指令或在使用屬性將「發佈」功能添加到您的指令範圍中 – Neozaru 2014-10-29 14:41:36
我想避免將服務注入到指令 – Fabrizio 2014-10-29 14:54:38
@Fabrizio,讓我直觀一點,您是否想從指令中觸發控制器上的單擊事件? – 2014-10-29 14:59:29