ディレクティブを持つ文字列を介して新しい要素を生成し (そのためコンパイルする必要があります)、そのディレクティブが "=" を介してコントローラー スコープ内の変数との関連付けを生成すると、コントローラー内の変数は、ディレクティブに 1 つ。
「ドア」の ng-model 値をすべてのディレクティブ モデル値に関連付ける必要がある例を示すために、jsfiddle を作成しました。
このフィドルを参照してください:http://jsfiddle.net/aVJqU/2/
私が気付いたもう 1 つのことは、html に存在する要素から実行されるディレクティブが、変数 (コントローラーとディレクティブ) を介して正しい関連付けを示していることです。
html (バインドするディレクティブがあります<door>
):
<body ng-app="animateApp">
<div ng-controller="tst">
<h2> Controller with its model </h2>
<input ng-model="doorval" type="text"> </input>
{{doorval}}
<h2> Directive render directly from the html </h2>
<door doorvalue="doorval"></door> <key></key>
<h2> Directives that are compiled </h2>
<list-actions actions="actions"></list-actions>
</div>
</body>
これはディレクティブです:
animateAppModule.directive('door', function () {
return {
restrict: "E",
scope: {
doorvalue:"="
},
template: '<span>Open the door <input type="text" ng-model="doorvalue"> </input> {{doorvalue}}</span>',
replace: true
}
})
これはコントローラーです:
var animateAppModule = angular.module('animateApp', [])
animateAppModule.controller('tst', function ($scope, tmplService) {
$scope.doorval = "open"
$scope.actions = tmplService;
})
animateAppModule.service('tmplService', function () {
return [{
form_layout: '<door doorvalue="doorval"></door> <key></key>'
}, {
form_layout: '<door doorvalue="doorval"></door> with this <key></key>'
}]
})
そして最後に、これはバインドしないディレクティブを持つ文字列をコンパイルするディレクティブです。
animateAppModule.directive('listActions', function ($compile) {
return {
restrict: "E",
replace: true,
template: '<ul></ul>',
scope: {
actions: '='
},
link: function (scope, iElement, iAttrs) {
scope.$watch('actions', function (neww, old,scope) {
var _actions = scope.actions;
for (var i = 0; i < _actions.length; i++) {
//iElement.append('<li>'+ _actions[i].form_layout + '</li>');
//$compile(iElement.contents())(scope)
iElement.append($compile('<li>' + _actions[i].form_layout + '</li>')(scope))
}
})
}
}
})
すべての「ドア」の ng-model 値を一緒にバインドするにはどうすればよいですか? コンパイルされたディレクティブはどこにバインドされていますか?