动态渲染角度模板

时间:2015-03-26 19:38:01

标签: jquery angularjs

需要建议我是否可以使用attr功能在data-ng-include上使用div设置模板 -

main.js中的代码 -

var app = angular.module('myApp', []);
app.controller('MyCtrl', function($scope) {
$scope.Values = [{"name":"John", "category":1},
{"name":"Jack", "category":1},
{"name":"Alina", "category":2},
{"name":"Joseph", "category":2}]

$scope.categoryMatch = function (item) {
            return item.category == $scope.currentCategory;
        }

$scope.currentCategory = 1;
$("#div1").attr("data-ng-include", "'htmlpage1.html'");
//above attr function does not assign template to div1

$scope.currentCategory = 2;
$("#div1").attr("data-ng-include", "'htmlpage1.html'");
//above attr function does not assign template to div2

});

htmlpage1.html

<div ng-repeat="value in Values  | filter:categoryMatch">
...do stuff...
</div>

index.html

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
</head>
<body ng-controller="MyCtrl">
    <div id="div1"></div>
    <div id="div2"></div>
</body>
</html>

如果这是正确的做法或者我是否遗漏了什么,能告诉我吗?基本上我需要attr函数才能在我的代码中工作。

1 个答案:

答案 0 :(得分:1)

ng-include不能与attr()一起使用,因为directives编译/加载的模板包含在控制器之前

您可以制作directive并使用attr()函数在指令的link()函数中指定指令

app.directive('exampleDirective', function() {
  return {
    restrict: 'E',

    controller: function($scope, $element){
      $element.attr('data-ng-include', 'bottom');
    },

  }
   })