[英]AngularJS custom directive with ngModel binding not working
我正在嘗試創建用於顯示格式化地址的自定義指令。 我已經編寫了以下代碼來使用new指令,但是它不起作用。 我的帳戶控制器(未顯示)工作正常,並且billingAddress.Line1正確顯示。 但是,我的address指令不呈現任何內容。
盡管我希望將指令代碼移到單獨的.js文件中以供重用,但我已將指令代碼包含在html中。 有人可以解釋我做錯了什么嗎?
<!DOCTYPE html> <html ng-app="myApp"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> <script type="text/javascript" src="ng-address.js"></script> <script type="text/javascript" src="app.js"></script> <script type="text/javascript"> (function() { var app = angular.module('ng-directives', []); app.directive("ngAddress", function() { return { restrict: 'E', scope: { address: '=ngModel' }, template: "<div>{{address.Line1}}</br><span>{{address.Line1}}</br></span>{{address.city}}, {{address.state}} {{address.postCode}}</div>" }; }); })(); </script> </head> <body class="container" ng-controller="AccountController as account"> <div>{{account.model.billingAddress.line1}}</div> <ng-address ng-model="account.model.billingAddress"></ng-address> </body> </html>
首先,示例不完整。
myApp
AccountController
as
無效。 我不確定這是否行得通,但我從未使用過。 該指令中的主要問題是ng-model
的錯誤使用。 您應該將其傳遞給require
,而不是傳遞給范圍。 然后將其傳遞給link
函數,在其中實現$render
函數。
您可能還希望將函數推送到$viewChangeListeners
。
有關更多詳細信息,請參見文檔 。
最后,模板包含</br>
,該模板無效。
<!DOCTYPE html> <html ng-app="myApp"> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script> <script type="text/javascript"> (function() { var app = angular.module('myApp', []); app.controller('AccountController', function($scope) { $scope.model = { billingAddress: { line1: 'somewhere far far away', city: 'Dark side of the moon', state: 'Top secret', postCode: '1337XD' } }; }); app.directive("ngAddress", function() { return { restrict: 'E', require: '?ngModel', template: "<div>{{address.line1}}<br><span>{{address.line1}}<br></span>{{address.city}}, {{address.state}} {{address.postCode}}</div>", link: function(scope, element, attrs, ngModel) { ngModel.$render = function() { scope.address = ngModel.$modelValue; }; } }; }); })(); </script> </head> <body class="container" ng-controller="AccountController"> <input class="form-control" ng-model="model.billingAddress.line1"/> <input class="form-control" ng-model="model.billingAddress.city"/> <input class="form-control" ng-model="model.billingAddress.state"/> <input class="form-control" ng-model="model.billingAddress.postCode"/> <ng-address ng-model="model.billingAddress"></ng-address> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.