[英]AngularJS ng-model in custom directives
我正在使用ng-model
創建指令。 因此,我可以將模型傳遞給這些指令。
這是我的想法:
app.js
app.directive('testDir', function(){
return {
templateUrl: 'assets/views/dir.html',
restrict: 'E',
required: 'ngModel'
};
});
dir.html
<div>
<h1>Test directive</h1>
<h3>{{name}}</h3>
</div>
index.html
<div class="container" ng-controller="testCtrl">
<test-dir ng-model="user"></test-dir>
</div>
和控制器
$scope.user = {
name: 'John Doe'
};
我可以看到帶有Test directive
文本的<h1>
標記,但在<h3>
標記中什么也沒有
我知道這是一個非常初學者的問題,但是正確的知道我找不到任何解決方案。
謝謝!
試試看,您需要為ng-model創建范圍變量
app.directive('testDir', function(){
return {
templateUrl: 'assets/views/dir.html',
restrict: 'E',
required: 'ngModel',
scope: {
ngModel:'='
}
};
});
的HTML
<div>
<h1>Test directive</h1>
<h3>{{ngModel}}</h3>
</div>
scope
的語法丟失。 請參見下面的工作示例
var app = angular.module("sa", []); app.controller("testCtrl", function($scope) { $scope.user = { name: 'John Doe' }; }); app.directive('testDir', function() { return { //templateUrl: 'assets/views/dir.html', template: '<div>' + '<h1>Test directive</h1>' + '<h3>{{fooModel.name}}</h3>' + '</div>', restrict: 'E', required: 'ngModel', scope: { fooModel: '=ngModel' } }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="sa" class="container" ng-controller="testCtrl"> <test-dir ng-model="user"></test-dir> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.