我正在尝试在 AngularJS 中制作一个指令小部件,我想传递一个名称、操作 k/v 对的数组来表示将在父 Controller 上触发操作的按钮。
到目前为止我已经尝试过:
<div data-collapse-widget data-title="Templates" data-widget-themis="false" data-color="grey" data-buttons="[new:'test']">
^HTML 中指令的开头
我的 javascript (coffeescript)
Module.directive 'collapseWidget', () ->
directive =
restrict: 'A'
transclude: true
template: viewCollapseWidget
scope:
title: '@title'
widgetThemis: '@widgetThemis'
color: '@color'
buttons: '&buttons'
replace: true
compile: (element, attrs, transclusionFunc) ->
(scope, iterStartElement, attrs) ->
scope.collapsed = false
scope.toggle = () ->
scope.collapsed = !scope.collapsed
origElem = transclusionFunc scope
content = origElem.text()
scope.orig = content
#scope.obj = my_custom_parsing(content)
scope.obj = content
但显然这是行不通的。有人知道我该怎么做吗?
最佳答案
我从帖子中看不出 viewCollapseWidget 是什么,但基本思想是在“父” Controller 中设置模型以包含您在
中的按钮对象<div data-collapse-widget>
因此,您可以简单地将模型值传递给指令,然后让按钮执行传递的函数。此方法还允许隔离指令作用域,而不是尝试弄脏父作用域。我发布了JsFiddle 以下内容:
插入指令后,您的 View 可能看起来像这样:
<div ng-controller="ParentCtrl">
<div collapse-widget
title="Show / Collapse"
buttons="model.buttons"></div>
</div>
Controller 逻辑和指令可能如下所示:
angular.module('main', [])
.controller("ParentCtrl", ['$scope', function( $scope ){
$scope.doSomething = function(){
alert('do something called from parent');
}
$scope.doSomethingElse = function(){
alert('do something else called from parent ');
}
$scope.model ={
buttons: {
'Test Button': $scope.doSomething,
'Another Button': $scope.doSomethingElse
}
}
}])
.directive("collapseWidget", function factory() {
return {
template: '<div ng-init="collapsed=true">'+
'<h2 ng-click="collapsed= {true: false, false: true}[collapsed]">{{title}}</h2>'+
'<button ng-hide="collapsed" '+
'ng-repeat="(name, fn) in buttons" ng-click="fn()">{{name}}</button>'+
'</div>',
replace: true,
restrict: 'A',
scope: {
title: "@",
buttons: "="
},
link: function postLink( scope, element, attrs ) {
//do something else here
}
};
});
关于javascript - AngularJS 创建指令并传入与父 Controller 中的操作相关的按钮的键/值对数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16138658/