我刚刚开始使用AngularJS,但我发现了一个我无法找到的小问题,我希望你偷看可以帮助我。
我导入了AngularJS Gridster,这是一种向网页添加动态网格的简单方法。现在一切正常,元素从数据库中成功加载并导入Gridster,但现在我想做以下事情。在从数据库检索的JSON中,还有一个名为“directive”的属性。现在,当所有内容都被加载时,我想在每个Gridster元素中添加从数据库返回的指令。
<ul>
<li gridster-item="item" ng-repeat="item in gridsterItems">
{{ item.directive }} // Returns <clock-widget></clock-widget> and print it to the screen, but it dont run the directive and doesn't display.
</li>
</ul>
现在它返回正确的值并在屏幕上显示字符串,但我想运行它指令clockWidget。
app.directive('clockWidget', function() {
return {
replace: true,
template: 'Yups, I am the clockwidget',
};
});
在网上我读了一些关于$ compile的内容,但我找不到。我希望你偷看可以帮助我。
谢谢!
答案 0 :(得分:2)
是的,您需要使用$compile
。请参阅documentation。
jsfiddle上的实例。
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope) {
$scope.directives = ["<directive-one></directive-one>", "<directive-two val='inputVal'></directive-two>"];
})
.directive('compileDirective', function($compile) {
return {
restrict: "E",
replace: true,
link: function(scope, element, attr) {
scope.$watch(function() {
return attr.directive;
}, function(val) {
element.html("");
if (val) {
var directive = $compile(angular.element(val))(scope);
element.append(directive);
}
});
}
};
})
//Directives for example
.directive('directiveOne', function($compile) {
return {
replace: true,
template: "<div>i'm directive one</div>"
};
})
.directive('directiveTwo', function($compile) {
return {
replace: true,
scope:{val:"="},
template: "<div>i'm directive two with val={{val}}</div>"
};
})
.directive('directiveThree', function($compile) {
return {
replace: true,
scope:{val:"="},
template: "<div>i'm directive three</div>"
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<select ng-model="selectDirective" ng-options="dir for dir in directives">
</select>
<input ng-model="inputVal">
<compile-directive directive="{{selectDirective}}"></compile-directive>
<compile-directive directive="<directive-three></directive-three>"></compile-directive>
</div>
</div>