在指令中单击按钮隐藏/显示div

时间:2014-05-02 05:16:56

标签: javascript jquery angularjs angularjs-directive

我正在尝试编写一个指令,我在其中提供按钮,以便当用户点击它时,一些内部div将被隐藏。但是我没有得到如何隐藏/显示clicked元素指令的动画,因为我的页面上有很多指令。

小提琴示例:: JSFiddle link

HTML ::

 <div class="col-md-7" id="middle_part">Middle<br/>
      <my-dir 
        bgcolor="gray"
        myTitle="Anam" 
        amount="29000"
        myheight="100"
        width="400"
        mycolor="cyan"
        save="saveChanges('custom directive')">template
      </my-dir>
  </div>

脚本::

// add a directive
app.directive("myDir", function() {
  return {
    restrict: "E",
    scope: {
      myTitle: "@",   // by value
      myheight: "@",   // by value
      mywidth: "@",   // by value
      mycolor: "@",   // by value
      bgcolor: "@",   // by value
      amount: "=", // by reference
      save: "&"    // event
    },
    template: 
      "<div><h2>  And This is Title <button ng-init='collapsed=true' ng-model='collapsed' ng-click='collapsed=!collapsed'>Save</button> " +
  "</h2><div  ng-show='collapsed' style='clear:both;'> This is dynamic content which i want to hide/show <br/><br/></div>" +
  "  {{myTitle}}+{{myheight}}:  </div>",
    replace: true,
    transclude: false,
    link: function (scope, element, attrs) {

        // show initial values: by-val members will be undefined
        console.log("background is " +attrs.bgcolor);


        // change element just to show we can
        element.css("background", attrs.bgcolor);
        element.css("color", attrs.mycolor);
        element.css("height", attrs.myheight);
        element.css("width", attrs.mywidth);


        // // log changes to the 'amount' variable
    }
  }
});

如何将hide / show与动画绑定?

1 个答案:

答案 0 :(得分:2)

您可以使用ngAnimate模块。首先添加依赖项:

var app = angular.module('plunker', ['ngAnimate']);

然后设置动画只是编写CSS过渡/动画的问题。例如:

.collapsible {
    -webkit-transition: all .6s linear;
    opacity: 1;
    background: #EFF;
    max-height: 150px;
}
.collapsible.ng-hide-add,
.collapsible.ng-hide-remove {
    display: block !important;
}
.collapsible.ng-hide-add-active,
.collapsible.ng-hide-remove-active {
    overflow: hidden;
}
.collapsible.ng-hide {
    opacity: 0;
    max-height: 0;
}

演示:http://plnkr.co/edit/2YgEceZkBRjbnEVds945?p=preview