从指令AngularJs触发控制器范围
我有一个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>
发布更改您的指令有这样onPublish: "@"
范围的额外项目然后在你的html中,你可以传递一个指向你想调用的控制器函数的指针,如下所示:
<share-post on-publish="publish"></share-post>
从指令调用这个你要做的:
$scope.onPublish()(ctrl.type, ctrl.ids, $scope.text)
这种方式是行不通的,因为如果我通过'publish'方法,你如何看到'share-post'指令是'timeline'的子节点,你如何显示它,试图获得父指令'publish'我猜。 – Fabrizio 2014-10-29 14:53:26
我错过了嵌套指令,您可以通过将控制器的函数传递给父指令,然后从那里传递给子控件来实现调用控制器方法。但是这有点令人讨厌。 另一种方法是在子指令和控制器中注入一个服务(一个新服务),这样你就可以使用它来沟通 – 2014-10-29 15:08:52
Yhea你解释了我说的更好,然后我说,从父指令指向子指令。非常感谢,你可以举一个小例子来介绍如何使用我可以加入沟通,指令和控制器的服务? – Fabrizio 2014-10-29 15:11:28
以及你用你的指令只是绑定从控制器的情况下点击,是这样的:
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>
我想你应该直接注入TimelineService服务到你的指令或在使用属性将“发布”功能添加到您的指令范围中 – Neozaru 2014-10-29 14:41:36
我想避免将服务注入到指令 – Fabrizio 2014-10-29 14:54:38
@Fabrizio,让我直观一点,您是否想从指令中触发控制器上的单击事件? – 2014-10-29 14:59:29