我正在嘗試創(chuàng)建一個(gè)指令,該指令將創(chuàng)建與創(chuàng)建指令的元素具有相同ng-model的輸入字段。到目前為止,這是我想到的:的HTML<!doctype html><html ng-app="plunker" ><head> <meta charset="utf-8"> <title>AngularJS Plunker</title> <link rel="stylesheet" href="style.css"> <script>document.write("<base href=\"" + document.location + "\" />");</script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script> <script src="app.js"></script></head><body ng-controller="MainCtrl"> This scope value <input ng-model="name"> <my-directive ng-model="name"></my-directive></body></html>的JavaScriptvar app = angular.module('plunker', []);app.controller('MainCtrl', function($scope) { $scope.name = "Felipe";});app.directive('myDirective', function($compile) { return { restrict: 'E', scope: { ngModel: '=' }, template: '<div class="some"><label for="{{id}}">{{label}}</label>' + '<input id="{{id}}" ng-model="value"></div>', replace: true, require: 'ngModel', link: function($scope, elem, attr, ctrl) { $scope.label = attr.ngModel; $scope.id = attr.ngModel; console.debug(attr.ngModel); console.debug($scope.$parent.$eval(attr.ngModel)); var textField = $('input', elem). attr('ng-model', attr.ngModel). val($scope.$parent.$eval(attr.ngModel)); $compile(textField)($scope.$parent); } };});但是,我不確定這是處理這種情況的正確方法,并且存在一個(gè)錯(cuò)誤,即我的控件未使用ng-model target字段的值初始化。這是上面代碼的簡稱:http ://plnkr.co/edit/IvrDbJ處理此問題的正確方法是什么?編輯:ng-model="value"從模板中刪除后,這似乎工作正常。但是,我將繼續(xù)公開這個(gè)問題,因?yàn)槲蚁朐俅未_認(rèn)這是正確的方法。
3 回答

12345678_0001
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
它并不那么復(fù)雜:在命令中,使用別名: scope:{alias:'=ngModel'}
.directive('dateselect', function () {
return {
restrict: 'E',
transclude: true,
scope:{
bindModel:'=ngModel'
},
template:'<input ng-model="bindModel"/>'
}
在您的html中,照常使用
<dateselect ng-model="birthday"></dateselect>
- 3 回答
- 0 關(guān)注
- 698 瀏覽
添加回答
舉報(bào)
0/150
提交
取消