AngularJS - Templates: ngInclude directive

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

For example, in my JS script.js file, I have methods that apply to HTML elements in my templtes, and this will not work, think about it, 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 runs well, I feel like it does not find the div # nav element.

+4
source share
3 answers

Sorry, I read the part of your question incorrectly, my mistake.

A ready-made jQuery DOM statement will probably not work correctly. What you can do is add the ngInclude tag to onload = "FUNCTION_NAME", which contains the version of the DOM specified inside script.js

For more information, see the documentation here: http://code.angularjs.org/1.0.1/docs-1.0.1/api/ng.directive:ngInclude

--- Old post ---

@YoussefElMontaser, you do not need to put quotes in ngInclude:

 <ng-include src="header.html"></ng-include> 

Perhaps it is not that your script is not moving forward. Let me know if this worked.

+2
source

The solution provided by Youssef can be made "more Angular", and it does 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 are trying to change the properties of a model (for example, $ scope.color) and automatically update the view. We try not to look for elements by jQuery identifiers or selectors, and we try to avoid manipulating the DOM in the controller - for example, $ ('# tpl2'). AddClass ('red');

+11
source

I found a solution:

http://jsfiddle.net/esjeY/

HTML

 <div ng-app=""> <div ng-controller="Ctrl"> <select ng-model="template" ng-options="t.name for t in templates"> <option value="">(blank)</option> </select> url of the template: <tt>{{template.url}}</tt> </div> <div ng-include src="template.url" onload='myFunction()'></div> </div> 

Js

 function Ctrl($scope) { $scope.templates = [{ name: 'template1.html', url: 'template1.html' }, { name: 'template2.html', url: 'template2.html' }]; $scope.template = $scope.templates[0]; $scope.myFunction = function() { $('#tpl2').addClass('red'); } } 

@guiligan: Thanks for your help.

+1
source

Source: https://habr.com/ru/post/1432247/


All Articles