【问题标题】:AngularJS - Optional required elementAngularJS - 可选的必需元素
【发布时间】:2012-12-23 09:47:57
【问题描述】:

我正在尝试使用自定义指令来制作有条件的必需语句。我添加的第一个条件是“firstInArray”,如果它是选择数组中的第一个元素,则使该元素成为必需元素(对于需要选择至少一个项目的 UI 是必需的,但您可以无限选择多个项目):

  .directive('variableRequired', [
    ()->
      return {
        require: 'ngModel',
        link: (scope, el, attrs, ctrl)->
          vars = attrs.variableRequired.split(',')
          condition = vars[0]
          if condition is 'firstInArray'
            item = vars[1]
            arr = vars[2]
            if scope[item] == scope[arr][0]
              $(el).removeAttr('variable-required')
              $(el).attr('required', 'required')
      }       
  ]) 

当我在指令中添加 scope.$apply() 时,应用程序会冻结(似乎是无限递归)。

有没有比自定义指令更好的方法来解决这个问题?如果不是,我的指令有什么问题?

【问题讨论】:

  • 可以添加一个html sn-p作为例子吗?

标签: coffeescript angularjs


【解决方案1】:

您也许可以使用undocumented ng-required 指令,而不是您自己的自定义指令:

<li ng-repeat="itemObj in items">
   <input type="text" ng-model="itemObj.text" ng-required="$first">
</li>

【讨论】:

  • 请注意,ng-required 现在已记录在案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多