簡體   English   中英

ng-model無約束的angular指令

[英]angular directive with ng-model not binding

我創建了一個名為<form-field>非常簡單的指令,我正在嘗試將ng-model綁定到該指令。 我已經將示例分解為最簡單的用例,

我已經包含了控制器,以及帶有HTML的指令。 我已經看到了許多require:ngModel的示例require:ngModel ,然后在link:內部執行了操作link:但所有這些示例僅適用於dom操作,或者例如不保存值的增量

 angular.module('taskApp', []) .controller('taskController', function($scope) { $scope.taskData = {}; $scope.save = function(taskData) { $scope.taskData = angular.copy(taskData); }; }) .directive('formField', function($timeout) { var template = '<div class="form-group" ng-switch="element">' + '<input ng-switch-when="input" ng-model="ngModel" name="{{field}}">' + '<textarea ng-switch-when="textarea" ng-model="ngModel" name="{{field}}"></textarea>' + '</div>'; return { restrict: 'EA', template: template, replace: true, scope: { ngModel: '=', field: '@', live: '@', element: '@' }, link: function($scope, element, attr) { } }; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="taskApp" ng-controller="taskController"> <form name='taskForm' novalidate> <form-field element='input' live='false' field="title" ng-model="taskData.title"></form-field> <form-field element='textarea' live='false' field="notes" ng-model="taskData.notes"></form-field> <button type="submit" ng-click="save(taskData)">save</button> </form> <br/> <pre>{{taskData | json}}</pre> </body> 

指令中的ngModel仍然引用內部隔離范圍。 您可以使用$parent.ngModel來訪問外部模型。

var template = '<div class="form-group" ng-switch="element">' +
  '<input ng-switch-when="input" ng-model="$parent.ngModel" name="{{field}}">' +
  '<textarea ng-switch-when="textarea" ng-model="$parent.ngModel" name="{{field}}"></textarea>' +
  '</div>';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM