2014-04-12 106 views
1

我傾向於AngularJS,專門研究學習指令。想要一個表單輸入指令,我可以在我的所有表單上重新使用它來封裝所有的鍋爐板標記。雖然我無法在我的指令中使用雙向綁定工作。它使用具有自己的內部屬性的隔離範圍來存儲輸入字段的值。我已經在該內部屬性上設置了一個監視,該屬性正確地將隔離範圍內的值推送到控制器範圍。我想弄清楚的是如何從控制器範圍中獲取初始值,並將其設置爲我的指令中的初始值。表單輸入指令與隔離範圍的雙向綁定

Plunker鏈接:http://embed.plnkr.co/TbVB0q9DHhBCVLQ4U64W/script.js

打字在第一輸入框中改變控制器作用域屬性,而不是指令值。在第二個輸入框中輸入更改指令和控制器屬性。

我知道這是可能的使用屬性來傳遞初始值。不過,我希望能夠通過我的指令中的ngModel引用從控制器作用域屬性中提取值。

編輯後回答:

對於那些不知道你爲什麼想通過學習指令的努力。尤其是當Angular甚至沒有使用指令時如此強大。這是一個很好的原因。

我表單上輸入字段,而指令:

<div class="form-group"> 
     <label for="firstName" class="col-sm-6 col-md-4 control-label">First Name</label> 
      <div class="col-sm-6 col-md-8" ng-class="{'has-error': userForm.firstName.$invalid}"> 
       <input type="text" id="firstName" name="firstName" placeholder="First Name" ng-model="muState.currentUser.firstName" class="form-control" required 
           popover="Cannot be blank" popover-trigger="{{{true: 'mouseenter', false: 'never'}[userForm.firstName.$invalid]}}" /> 
      </div> 
</div> 

用我的指令後:

<ws-form-input input-name="firstName" input-label="First Name" input-placeholder="First Name" 
       ng-model="muState.currentUser.firstName" 
       required input-error="Cannot be blank"></ws-form-input> 

經過努力。之後您將面臨學習與維修噩夢的交鋒。

回答

2

我想你可以通過使用隔離示波器的'='屬性的符號完全簡化您的指令。

事情是這樣的:

JAVASCRIPT

app.directive('inputDirective',function(){ 
    return { 
     restrict: 'E', 
     replace: true, 
     scope: {ngModel: '='}, 
     templateUrl: "directiveTemplate.html", 
     require: '^form', 
     link: function(scope, elem, attrs, ctrl){ 
      scope.form = ctrl; 

      scope.required = false; 
      // If attribute required exists 
      if (attrs.required !== undefined) {      
       // ng-required takes a boolean which is read from this scope variable 
       scope.required = true; 
      } 
     } 
    }; 
}); 

HTML DIRECTIVE

<div> 
<input type="text" id="directiveInput" 
     ng-model="ngModel" class="form-control" ng-required="required"/> 

<br/> 
Isolated Scope value of the input box: {{ngModel}} 
</div> 

UPDATED PLUNKER

+0

我可以發誓,我試過這個。但如果我有的話,不會在這裏。這絕對會使指令中的代碼更加清晰。謝謝! – ACanadian

0

您必須執行ngModel.$render,請參閱參考here

在你的指令,下面的代碼就足夠了:

scope.ngModel.$render = function() { 
    scope.inputBinding = scope.ngModel.$viewValue; 
}; 
+0

我不知道ngModel $渲染。 !肯定會學到一些關於在隔離範圍內使用ngModel的知識。 – ACanadian

相關問題