我有一个TimelineController
在作用域上有一个publish
函数,它会将一些数据发送到服务器。
我的时间轴由2 directives
我希望能够通过share-post
指令来调用我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>
答案 0 :(得分:1)
你使用你的指令只是为了从控制器绑定事件点击,如:
angular.module('module').directive('sharePost', [
function(){
return {
link: function (scope, element, attr) {
var clickAction = attr.clickAction;
element.bind('click',function (event) {
scope.$eval(clickAction);
});
}
};
}]);
<强> HTML 强>
<a sharePost click-action="publish(wall_type,wall_id,text,video,image)"> publish</a>
答案 1 :(得分:0)
更改你的指令以在范围内有一个额外的项目,如onPublish: "@"
,然后在你的html中你可以传递一个指向你想要调用的控制器函数的指针:
<share-post on-publish="publish"></share-post>
从您必须执行的指令中调用它:
$scope.onPublish()(ctrl.type, ctrl.ids, $scope.text)