如何在AngularJS指令中切换模板用法?

时间:2014-02-19 07:54:36

标签: javascript angularjs

我有一个使用模板和ng-transclude的自定义指令。传入事件应切换指令模板的使用。 如果启用了模板,则指令应呈现为“正常”,但如果禁用模板,则应仅显示已转换的内容。

如何扩展指令以实现此行为?

您可以在http://plnkr.co/edit/tKag6y上找到整个示例。

<custom-directive>
  <label>Name:</label>
  <input text="text" ng-model="yourName" placeholder="Enter a name here">
  <hr>
  <h1>Hello {{yourName}}!</h1>
</custom-directive>
.directive('customDirective', ['$rootScope',
  function($rootScope) {

    return {
      restrict: 'E',
      transclude: true,
      replace: true,
      scope: {},
      controller: function($scope, $element) {
        $scope.edit = function() {
          alert('Edit content!');
        }

        $rootScope.$on('toggleMenu.enableEditMode', function() {
          alert('Edit mode: Enable template!');

          // How to update the directive here?
        });

        $rootScope.$on('toggleMenu.disableEditMode', function() {
          alert('View mode: Disable template!');

          // How to update the directive here?
        });
      },
      template: '<div class="panel panel-default">' +
        '<div class="panel-body" ng-transclude></div>' +
        '<div class="panel-footer">' +
        '<button class="btn btn-warning" ng-click="edit()"><span class="glyphicon glyphicon-pencil"></span>&nbsp;Edit</button>' +
        '</div></div>'
    };
  }
])

0 个答案:

没有答案