我在一個我爲下拉替換寫的指令中有一個非常奇怪的行爲。使用的模型可以使用子節點無限嵌套。 (HAML-Code):AngularJS:指令的模板不能正確渲染
.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" }
正如我到目前爲止所遇到的,該模型的行爲是絕對正確的!在調試視圖中或者通過console.log或者$ log whatever,但是指令的渲染會變得混亂起來,顯示項目翻倍或者甚至倍增,取決於您切換下拉的次數。
咖啡劇本是這樣的,這是很容易的代碼:該指令的
# 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
}
]
視圖模板代碼得到由它寫在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'" }
我沒有與這只是一個問題的任何第二個下拉不正確地更新其觀點,型號不對。我想知道你能不能幫助或看到一些不合法的東西。
親切的問候, 亞歷
只是好奇,爲什麼你使用on-change而不是ng-change? – jpmorin
我對HAML並不熟悉,但是按照你的縮進,這是我的理解:你首先在'ul'的內部循環'div',在'div'裏面放置'li'。在你循環的'ul'上有'li'的兄弟,你在'ul'中使用'div'來啓動下一個子級別......當我看到它時,你的層次結構如下所示: 'ul > DIV [循環]> [li>系統| UL [循環]> DIV> [li>系統| UL [循環]> DIV ...'。 AFAIK,這不是有效的HTML。 'ul'中唯一有效的元素是'li'。 – jpmorin
我確實使用on-change,因爲指令讀取的值是在自定義作用域中調用的回調函數$ watch ...我不想混淆該指令的其他用戶的ng-change,因爲ng-change是原生指令... 是的,我知道這是不好的HTML。原因是增加了一些能夠接收正確項目的塊。我將在下面檢查你的帖子。非常感謝。 – sp33c