我为下拉替换编写的指令中有一个非常奇怪的行为。使用的模型可以使用子节点无限嵌套。该指令的包含方式如下(HAML 代码):
.control-group
-# use the angular directive "dropdown-tree" that can handle unlimited nested models!
.controls{ "dropdown-tree" => "", "ng-model" => "categories_as_tree", "current-value" => "currentCategory", "dropdown-placeholder" => "choose category", "ng-disabled" => "!categories || categories.length==0", "on-change"=>"fetchProducts(category)" }
%h4 Products
.control-group
.controls{ "dropdown-tree" => "", "ng-model" => "products_as_tree", "current-value" => "currentProduct", "dropdown-placeholder" => "choose product", "ng-disabled" => "!products || products.length==0" }
正如我到目前为止所遇到的,该模型的行为绝对正确!在调试 View 中或通过 console.log 或 $log 等方式,但指令的渲染会变得困惑,显示项目翻倍甚至成倍增加,具体取决于您切换下拉列表的次数。
CoffeeScript 如下所示,代码很简单:
# use array -> being resistend against uglifiers mangle
mymodule.directive 'dropdownTree', [ ->
return {
templateUrl: '/angular/templates/dropdown_tree'
,
#require: 'ngModel', # don't need that so far, we keep things simple!
scope: {
ngModel: '=',
dropdownPlaceholder: '@',
currentValue: '=',
ngDisabled: '=',
onChange: '&'
},
link: (scope, element, attr, ngModelCtrl) ->
# fake the ng-change
scope.$watch('currentValue', ->
scope.onChange()
, true)
scope.selectValue = (value) ->
scope.currentValue = value
}
]
指令的 View 模板代码由 Rails Controller 传递 它是用 HAML 编写的,看起来像这样。如果子节点存在,它使用无限嵌套:
.btn-group{ :name => "FIXME", "ng-required" => "true" }
%a.btn.btn-default.dropdown-toggle{ "data-toggle" => "dropdown", href: "#", "ng-disabled"=>"ngDisabled" }
{{currentValue.name || dropdownPlaceholder }}
%span.caret
%ul.dropdown-menu{ "ng-show" => "!ngDisabled" }
%div{ "ng-repeat" => "model in ngModel", "ng-include" => "'node.html'" }
%script{ :type => "text/ng-template", :id => "node.html" }
%li{ "ng-click" => "selectValue(model)" }
%a
{{model.name}}
%ul{ "ng-repeat" => "model in model.children", :style => "margin-left: 10px;" }
%div{ "ng-include" => "'node.html'" }
我对此没有任何问题,只是第二个下拉列表没有正确更新其 View ,而模型却如此。我想知道您是否可以提供帮助或查看一些不合法的内容。
亲切的问候, 亚历克斯
最佳答案
如果您在彼此之间嵌套了 ng-repeats,那么它呈现奇怪的原因可能是您对彼此之间的重复使用相同的名称。如果您这样做,您实际上会在 DOM 树中向下移动时覆盖该引用。
关于javascript - AngularJS:指令的模板未正确渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338052/