Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Templates : ngInclude directive

Tags:

angularjs

My templates contain JS, as they are called JS is not executed, you have an idea please.

For example in my JS file script.js, i have methods that apply to HTML elements in my templtes and it does not work, an idea please.

Example :

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body ng-app>
    <ng-include src="'header.html'"></ng-include>
    <script src="angular.js"></script>
    <script src="jquery.js"></script>
    <script src="script.js"></script>
</body>
</html>

header.html

<div id="header">
<div id="logo">AngularJs</div>
<div id="nav"></div>
</div>

script.js

$(document).ready(function(){
    $('#nav').html('<ul><li><a href="">Link<a></li></ul>');
});

The script execute well, I feel it does not find the element div#nav.

like image 855
Youssef El Montaser Avatar asked Dec 09 '22 21:12

Youssef El Montaser


1 Answers

The solution provided by Youssef can be made "more Angular", and it will not require jQuery:

<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
    <p ng-class="color">Content of template2.html</p>
</script>

$scope.myFunction = function() {
    $scope.color = 'red';
}

http://jsfiddle.net/mrajcok/MfHa6/

In the Angular world, we try to change model properties (e.g., $scope.color) and let the view update automatically. We try to not look up elements by ID or jQuery selectors, and we try to avoid DOM manipulation in the controller -- e.g., $('#tpl2').addClass('red');

like image 171
Mark Rajcok Avatar answered Dec 29 '22 11:12

Mark Rajcok