大佬教程收集整理的这篇文章主要介绍了angularjs – 在元素中插入一个有角度的js模板字符串,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
HTML
<div ng-controller="TESTController"> <div ng-bind-html-unsafe="fruitsView"></div> </div>
控制器:
function filterController($scopE){ ... $scope.arr = ["APPLE","BANANA"]; $scope.fruitsView = '<div><p ng-repeat="each in arr">{{each}}</p></div>'; }
var tpl = $compile( '<div><p ng-repeat="each in arr">{{each}}</p></div>' )( scope );
正如你所看到的,$ compile返回一个函数,它将一个作用域对象作为参数,对其进行代码评估。例如,可以将结果内容插入到带有element.append()的DOM中。
重要说明:但是在任何情况下,任何与DOM相关的代码都不属于您的控制器。适当的地方总是一个指令。这个代码可以很容易地被引入到一个指令,但我不知道为什么你在程序中插入所有的HTML。
你能在这里散发一些光,@R_152_9447@提供一个更具体的答案吗?
更新
假设您的数据来自服务:
.factory( 'myDataservice',function () { return function () { // obvIoUsly would be $http return [ "Apple","Banana","Orange" ]; }; });
.factory( 'myTplservice',function () { return function () { // obvIoUsly would be $http return '<div><p ng-repeat="item in items">{{item}}</p></div>'; }; });
然后创建一个简单的指令,读取提供的模板,编译它,并将其添加到显示:
.directive( 'showData',function ( $compile ) { return { scope: true,link: function ( scope,element,attrs ) { var el; attrs.$observe( 'template',function ( tpl ) { if ( angular.isDefined( tpl ) ) { // compile the provided template against the current scope el = $compile( tpl )( scope ); // stupid way of emptying the element element.html(""); // add the template content element.append( el ); } }); } }; });
然后从您的视图:
<div ng-controller="MyCtrl"> <button ng-click="showContent()">Show the Content</button> <div show-data template="{{templatE}}"></div> </div>
在控制器中,你只需将它们绑在一起:
.controller( 'MyCtrl',function ( $scope,myDataservice,myTplservice ) { $scope.showContent = function () { $scope.items = myDataservice(); // <- should be communicated to directive better $scope.template = myTplservice(); }; });
它应该都在一起工作!
以上是大佬教程为你收集整理的angularjs – 在元素中插入一个有角度的js模板字符串全部内容,希望文章能够帮你解决angularjs – 在元素中插入一个有角度的js模板字符串所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。