[英]How can I get programmatic markup into my Angular page?
在我的Angular應用(1.4)中,我在網格中有一個控件,該控件可能是以下幾種之一,因此我創建了一個javascript函數來執行邏輯並吐出應該輸入的標記。
但是,它不能正常工作。 標記將呈現,但是其中似乎沒有Angular掛鈎。 以我有限的理解,我認為原因與摘要循環/定時有關。 我也懷疑我的代碼應該在指令中,但不確定。
我創建了一個小樣,演示了這個問題。 https://plnkr.co/edit/nuxFzqN0n6XgSHqmC6jK?p=info這是標記。 訪問插件查看js並運行它:
<body ng-controller="MainCtrl">
<div>Button1: <input type="button" value="Button 1" ng-click="button1click()"/><span ng-show="showButton1Result">BUTTON 1 CLICKED!</span></div>
<div>Button2: <span ng-bind-html="button2Markup()"></span></div>
<div>Button3: {{ button3Markup }}</div>
</body>
你明白了。 最好的方法是什么?
這在其他地方得到了回答: 編程角度模板?
指令是您要使用的指令:
<div>Button 2: <div programatic-button="button2Markup()"></div></div>
<div>Button 3: <div programatic-button="button3Markup"></div></div>
.directive('programaticButton', function($compile) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var html = scope.$eval(attrs.programaticButton);
var newElement = $compile(html)(scope);
element.append(newElement);
}
};
});
如前所述,您應該使用directive
。 以您的pl為起點,可能類似於以下內容。
HTML文件
<body ng-controller="MainCtrl">
<my-buttons type="type"></my-buttons>
<br>
<my-buttons type="2"></my-buttons>
</body>
的JavaScript
angular.module('plunker', [])
.directive('myButtons', function() {
return {
scope: {
type: '='
},
templateUrl: 'my-buttons-tpl.html',
link: function(scope) {
scope.click = function() {
scope.clicked = !scope.clicked;
};
}
};
})
.controller('MainCtrl', function($scope) {
$scope.type = 1;
});
其中my-buttons-tpl.html
<span ng-if="type === 1">
<input type="button"
value="Button 1"
ng-click="click()">
</span>
<span ng-if="type === 2">
<input type="button"
value="Button 2"
ng-click="click()">
</span>
<span ng-show="clicked">button type {{ type }} haz ben clicked</span>
我相信ng-bind-html
實際上不會在插入的代碼內綁定任何角度功能。
正如您在Angular源代碼中看到的那樣,內容只是放置在HTML元素內,沒有其他幻想。
我認為您絕對應該在這種情況下重新考慮使用ng-bind-html
,而應考慮使用指令
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.