gpt4 book ai didi

javascript - 从指令 AngularJs 触发 Controller 范围

转载 作者:行者123 更新时间:2023-12-03 11:33:31 26 4
gpt4 key购买 nike

我有一个 TimelineController,它在作用域上有一个 publish 函数,它将向服务器发送一些数据。

我的时间线由 2 个指令组成

  • 时间线(元素)
  • 分享帖子(元素)

我希望能够从 share-post 指令调用 TimelineController 上的 publish 函数,这可能吗?

Controller

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>

最佳答案

那么您使用指令只是为了绑定(bind)来自 Controller 的事件点击,例如:

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>

关于javascript - 从指令 AngularJs 触发 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26633092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com