我有一个 Angular 应用程序,它看起来像 iPad 应用程序。有一个带有按钮和下拉菜单的导航栏。导航栏在我的index.html 文件中声明。现在在我的不同页面中,我想向导航栏添加功能。现在我正在向导航栏添加按钮,如下所示
$rootScope.actionButtons.push({
icon: 'icon-history',
content: '<select ng-change="previewRevision()" ng-model="revision">\
<option value="">--Backlog--</option>
<option ng-repeat="old in journal.backlog" value="{{old.revision}}">Revision {{old.revision}}</option>
</select>',
title: 'Visa backlog'});
按下导航栏中的按钮时,此 View 中的内容会在弹出窗口中打开。 但是,由于用于呈现按钮的标记位于 Controller 外部,因此没有数据绑定(bind)到它,这使得它有点无用。
如何绑定(bind)当前范围之外的数据?
最佳答案
Angular 不知道您的内容。为了使其工作,我们需要使用 $compile
服务来编译这个源代码。
所以让我们创建“编译器”:
.directive( 'compileData', function ( $compile ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
var elmnt;
attrs.$observe( 'template', function ( myTemplate ) {
if ( angular.isDefined( myTemplate ) ) {
// compile the provided template against the current scope
elmnt = $compile( myTemplate )( scope );
element.html(""); // dummy "clear"
element.append( elmnt );
}
});
}
};
});
向 HTML 添加指令,例如:
<div compile-data template="{{actionButtons.content}}"></div>
编译后,您将使用下面提到的 HTML 绑定(bind)您的范围
<select ng-change="previewRevision()" ng-model="revision">\
<option value="">--Backlog--</option>
<option ng-repeat="old in journal.backlog" value="{{old.revision}}">Revision {{old.revision}}</option>
</select>
希望对你有帮助
关于javascript - Controller 外部的 Angular 绑定(bind)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19139347/