我正在嘗試創建一個指令,該指令將創建與創建指令的元素具有相同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); } };});但是,我不確定這是處理這種情況的正確方法,并且存在一個錯誤,即我的控件未使用ng-model target字段的值初始化。這是上面代碼的簡稱:http ://plnkr.co/edit/IvrDbJ處理此問題的正確方法是什么?編輯:ng-model="value"從模板中刪除后,這似乎工作正常。但是,我將繼續公開這個問題,因為我想再次確認這是正確的方法。
3 回答

12345678_0001
TA貢獻1802條經驗 獲得超5個贊
它并不那么復雜:在命令中,使用別名: 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 關注
- 687 瀏覽
添加回答
舉報
0/150
提交
取消