2012-12-26 40 views
0

我想建立一個指令,可以讓我在一個標籤使用Twitter的引導組件:AngularJS指令Twitter的引導

標籤看起來是這樣的:

   <bootstrapinput 
        model="lastName" 
        key="lastName" 
        localized="Surname" 
        formpath="playerForm.lastName" 
        required> 
       </bootstrapinput> 

該指令看起來像這樣

.directive('bootstrapinput', function() { 
    return { 
     restrict:'E', 
     compile:function (tElement, tAttrs, transclude) { 
      var type = tAttrs.type || 'text'; 
      var required = tAttrs.hasOwnProperty('required') ? 'required' : ''; 
      var ngClazz = tAttrs.hasOwnProperty('formpath') ? 'ng-class="{error: ' + tAttrs.formpath + '.$invalid}"' : ''; 
      var html = '<div class="control-group" ' + ngClazz + '>' + 
       '<label class="control-label" for="' + tAttrs.key + '">' + tAttrs.localized + '</label>' + 
       '<div class="controls">' + 
       '<input ng-model="'+tAttrs.model+'" type="' + type + '" id="' + tAttrs.key + '" name="' + tAttrs.key + '" placeholder="' + tAttrs.localized + '" ' + required + ' />' + 
       '</div>' + 
       '</div>'; 

      tElement.replaceWith(html); 


     } 


    } 

}); 

該標籤嵌入在控制器中。但是如果我通過示波器訪問控制器中的模型,則模型是空的。 此外,不評估ng-class屬性,即CSS未按原樣分配。

編輯現在可以訪問模型。但是ng-class屬性仍然沒有被正確評估。

+0

看到你可能會從使用[$編譯](http://docs.angularjs.org/api/ng.$compile)服務中受益。 – Humberto

+0

你對'ng-class'屬性有什麼期待?基於ngClazz變量,如果'formpath'屬性存在,它看起來像'ng-class'將是一個空字符串。 – Humberto

+0

如果表單元素無效(它在開頭處),則該div的CSS類應該是「error」(用於twitter引導程序)。該機制只有在設置了禁止時纔有效。在生成的HTML中,ng-class被正確設置。但由於某種原因,造型不是。 – Soccertrash

回答

0

使用$編譯。 transclude恕我直言,是沒有必要的:

app.directive("bootstrapinput", function($compile) { 
    return { 
     restrict: 'E', 
     scope: { 
      model: '=' 
     }, 
     link: function(scope, element, attrs) { 
      var type = attrs.type || 'text'; 
      var required = attrs.hasOwnProperty('required') ? 'required' : ''; 
      var ngClazz = attrs.hasOwnProperty('formpath') ? 'ng-class="{error: ' + attrs.formpath + '.$invalid}"' : ''; 
      var htmlTemplate = '<div class="control-group" ' + ngClazz + '>' + '<label class="control-label" for="' + attrs.key + '">' + attrs.localized + '</label>' + '<div class="controls">' + '<input ng-model="' + attrs.model + '" type="' + type + '" id="' + attrs.key + '" name="' + attrs.key + '" placeholder="' + attrs.localized + '" ' + required + ' />' + '</div>' + '</div>'; 
      console.log(htmlTemplate); 
      var compiled = $compile(htmlTemplate)(scope); 

      element.replaceWith(compiled); 
     } 
    }; 
}); 
+0

我根據您的建議修改了我的解決方案:http://jsfiddle.net/b9B8S/3/ CSS錯誤類仍然不起作用。此外,我必須忽略範圍:{model:'='}否則它不起作用 – Soccertrash

+0

通過編譯,大部分樣式工作良好,但「錯誤」類仍未提供:http://jsfiddle.net/JNgN2/5 / – Soccertrash

0

OK,我終於有解決方案

我剛剛結束的股利控制組在進一步DIV。現在它可以工作。

'<div><div class="control-group" ...>...</div></div>' 

http://jsfiddle.net/JNgN2/6/