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.

4
  • this is really risky. why don't you just assign the template value off of scope? Commented Mar 26, 2015 at 19:42
  • Don't use jQuery. Just write a directive. Commented Mar 26, 2015 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 Commented Mar 26, 2015 at 19:49
  • You can read up on how to write a directive here: docs.angularjs.org/guide/directive . Also, this will be a good read for you: stackoverflow.com/questions/14994391/… Commented Mar 26, 2015 at 19:50

1 Answer 1

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');
    },

  }
   })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.