【问题标题】:ng-style working initally but not on variable updateng-style 最初工作但不在变量更新上
【发布时间】:2017-05-28 22:50:02
【问题描述】:

在将 ng-style 与变量一起使用时,我遇到了一个奇怪的错误/行为,它适用于最初为其设置的任何值,但是当我更新变量时,视图不会按照应有的方式更新。我可以找到类似的问题,但在完全相同的情况下没有。我有(简化): 一个指令:

directives.directive('myAccordion', function{
  return {
   templateUrl: '/mytemplate.html';
   link: function($scope){
    'use-strict';
     scope.current_style '{\'max-height\':\'\'0px'}';
     scope.somefunc = function{
       isopen = !isopen;
       if(isopen){
         scope.current_style = '{\'max-height\':\'\'1000px'}';
       }else{
         scope.current_style = '{\'max-height\':\'\'0px'}'; 
     }
  };

在模板html中

etc etc
<div class="myclass" ng-style="{{current_style}}">
   <button ng-click="somefunc()"></button> 
</div>
etc

所以一切正常,包括我最初设置 current_style 的任何值,当显示 current_style 的值时,当单击按钮并调用 somefunc() 时,变量实际上会更改为正确的文本,但是 ng-样式不会更新,并且 div 保持相同的大小。 我不确定我在这里错过了什么。 感谢您的帮助

【问题讨论】:

  • 您将其分配给“全局”变量current_style。请改用$scope.current_style = ..。另外我认为ng-style="{{}}" 中的大括号不是必需的。您还应该知道您的 isOpen 变量被用作全局变量
  • 好吧,代码简化了,变量实际上都属于一个对象(使用对象构造函数创建),所以在实际代码中,current_style 是对象的一部分,然后在范围内创建(scope.accordion1 = new 手风琴) 所以这不是问题,也许我应该更新代码来表示它

标签: javascript html css angularjs ng-style


【解决方案1】:

你可以只使用ng-style的对象表示法:

scope.current_style = { 'max-height': '0px' };

scope.somefunc = function() {
    isopen = !isopen;
    if(isopen){
        scope.current_style["max-height"] = '1000px';
    } else {
        scope.current_style["max-height"] = '0px';
    }
}

在你的 html 中:

<div class="myclass" ng-style="current_style">
    <button ng-click="somefunc()"></button> 
</div>

this jsfiddle

【讨论】:

  • 这已经解决了,非常感谢!出于兴趣,知道它以前不起作用的特定原因吗?
  • 我认为这是因为您的字符串表示法,例如一个用引号括起来的对象,它只代表一个字符串
【解决方案2】:

请尝试以下,它更干净一点

if(isopen){
  scope.height= 1000;
}else{
  scope.height= 0; 
}


<div class="myclass" ng-style="{'max-height' : height + 'px'}">

要让代码更简洁,请使用以下代码:

scope.heignt = isopen ? 1000 : 0; 

需要维护的代码更少:)

【讨论】:

  • 好吧,这可能是一种更清洁的方法,但不幸的是并没有解决问题(刚刚尝试过希望它会)
猜你喜欢
  • 1970-01-01
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 1970-01-01
  • 2016-07-05
  • 2016-12-24
  • 2016-08-26
相关资源
最近更新 更多