2

我正在尝试在 AngularJS 中创建一个指令小部件,并且我想传入一个名称数组,动作 k/v 对来表示将触发父控制器上的动作的按钮。

到目前为止我已经尝试过:

<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

但显然这不起作用。有人知道我该怎么做吗?

4

1 回答 1

2

我从帖子中看不到 viewCollapseWidget 是什么,但基本思想是在“父”控制器中设置模型以包含您在您的

<div data-collapse-widget>

因此,您可以简单地将模型值传递给指令,然后让按钮稍后执行传递的函数。此方法还允许隔离指令范围,而不是试图弄脏父范围。我发布了以下内容的JsFiddle

插入指令后,您的视图可能看起来像这样:

<div ng-controller="ParentCtrl">
   <div collapse-widget 
        title="Show / Collapse" 
        buttons="model.buttons"></div>
</div>

控制器逻辑和指令可能如下所示:

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
    }
  };
});
于 2013-04-22T06:53:54.330 回答