0

Need a suggestion on whether i can use attr function to asign template using data-ng-include on a div -

Code in 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>

Can you please let me know if this is the correct way of doing this or whether i am missing anything? basically i need attr function to work in my code.

user979189
  • 1,230
  • 2
  • 15
  • 39
  • this is really risky. why don't you just assign the template value off of scope? – Daniel A. White Mar 26 '15 at 19:42
  • Don't use jQuery. Just write a directive. – David says Reinstate Monica Mar 26 '15 at 19:45
  • @DavidGrinberg - Can you please give a sample code of writing a directive for my problem? Basically i need to load the same template on multiple locaitons on same page based on the category in the Values array. I apologize i am new and trying to learn angular – user979189 Mar 26 '15 at 19:49
  • You can read up on how to write a directive here: https://docs.angularjs.org/guide/directive . Also, this will be a good read for you: http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background – David says Reinstate Monica Mar 26 '15 at 19:50

1 Answers1

1

ng-include will not work with attr() because directives are compiled/loaded templates are included before the controllers

you can make an directive and use attr() function to assign the directive in link() function of the directive

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

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

  }
   })
A.B
  • 20,110
  • 3
  • 37
  • 71