2013-04-09 102 views
2

我正試圖在未來某個時間將所需的指令添加到元素。 在該示例中,如果模型字段很髒,則需要使用該元素。 我試圖設置所需的屬性(有點樂觀) 我現在正在編譯和鏈接元素,並嘗試用新元素替換舊元素。將指令添加到現有元素

我的元素剛剛從頁面中消失? 我正在以正確的方式去做這件事嗎?

app.directive('requiredIfDirty', function ($compile, $timeout) { 
         return { 
          restrict: "A", 
          require: // element must have ng-model attribute. 
          'ngModel', 
          link: // scope = the parent scope 
          // elem = the element the directive is on 
          // attr = a dictionary of attributes on the element 
          // ctrl = the controller for ngModel. 
          function (scope, elem, attr, ctrl) { 
           var unsubscribe = scope.$watch(attr.ngModel, function (oldValue, newValue) { 
            if(angular.isUndefined(oldValue)) { 
             return; 
            } 
            attr.$set("required", true); 
            $timeout(function() { 
             var newElement = $compile(elem)(scope); 
             elem.replaceWith(newElement); 
            }, 1); 
            unsubscribe(); 
           }); 
          } 
         }; 
        }); 

回答

-2

你實際上不需要那麼做。角實際上有一個指令ng-required

看到

http://docs.angularjs.org/api/ng.directive:input.text

可以提供一個表達到NG-需要對具有基於表達式NG-模型,它會在需要驗證添加到任何領域評估爲真。

從文檔

ngRequired(可選) - {string=} - 添加必需的屬性和 需要驗證約束到元件時ngRequired 表達式評估爲真。當您要將數據綁定到必需的屬性時,請使用ngRequired而不是必需的 。

+3

它只是一個例子,問題仍然是如何動態地向現有元素添加指令。感謝所需的指針 – 2013-04-10 02:47:49

相關問題