AngularJS directive templateUrl - javascript

I am challenged to AngularJS that but does not work occurred.
I've created a code that uses the directive.
However, when you use the templateUrl, it does not do what we want to do the operation.
In my code, I am assuming that the tag is replaced by the contents of header.html. However, you can not.
Please lend your wisdom.
sample.html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
<script type="text/javascript">
var directiveApp = angular.module('dApp', []);
directiveApp.directive('header', [function () {
return {
restrict: 'E',
templateUrl: "header.html",
};
}]);
</script>
<body ng-app="dApp">
<header></header>
</body>
header.html
<label>Hello!</label>

With templateUrl in directive, angular will send a http request to retrieve this html from you server side. So you should make sure there is such 'header.html' file in the correct url.
However, if you don't want to load this template with a ajax. Then you can use the template in angular.
Add this to your sample.html:
<script type="text/ng-template" id="header.html">
<label>Hello!</label>
</script>
Hope this work for you.

Related

Pass AngularJS variable to script tag in html view

Here's the issue. I have a 3rd party script which needs to be embedded on my AngularJS app, in the html as a <script> tag. I need to pass scope variables to this script (name, email etc). My first attempt here is to figure out if I can pass a scope variable from the controller to a script tag on page load. Perhaps there's a better approach, like making the script a template, but I'm not sure. I'm worried that if I succeed in this basic concept, that the script tag will render the real data before the variable is passed.
Here's the HTML:
<body>
<div ng-controller="MainCtrl">
Angular variable: {{foo}}
</div>
</body>
<script type="text/javascript">
console.log(foo); // $scope.foo?
</script>
Here's the controller:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.foo = 'bar';
})
Plunker: https://plnkr.co/edit/5rcnqUxHRHMthHmkwVuZ?p=preview
If you want to embed third party script(jQuery plugin or something else) to your AngularJS application you should write wrapper to this script(simple directive or component)
The way you presented will not work - I guarantee
I found a simple example for you how to create AngularJS directive and wrap some simple jquery plugin:
<html>
<head>
<title>AngularJS wrapp jquery plugin</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://raw.github.com/SamWM/jQuery-Plugins/master/numeric/jquery.numeric.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.directive('numberMask', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
$(element).numeric();
}
}
});
</script>
</head>
<body>
<div ng-app="myApp">
<div>
<input type="text" min="0" max="99" number-mask="" ng-model="message">
</div>
</div>
</body>

Get data from controller to Component AngularJs

I have a problem. I create a component in AngularJs and I want to pass data from controller to Component.
Data comes to template component, but in the controller on component is undefined!
This is my code.
The controller
angular.module('testModule')
.controller('testController', ['$scope',
function($scope){
var vm = this;
vm.name = "John";
}
]);
The component. Here in the console.log(vm.name) its undefined! This is my problem.
angular.module('testModule')
.component('testComponent', {
bindings: {
"name": '='
},
controllerAs: 'ctrl',
controller: ['$scope', function ($scope) {
var vm = this;
console.log(vm);
console.log(vm.name);
}],
template: "<h2>Hi {{ctrl.name}}</h2>",
});
HTML
<html ng-app="testModule">
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script>
<script src="app.module.js"></script>
<script src="testController.js"></script>
<script src="testComponent.js"></script>
</head>
<body>
<div ng-controller="testController as ctrl">
<test-component name="ctrl.name"></test-component>
</div>
</body>
</html>
Here is the Plunker
Any idea? Thanks!
You should be hooking up over $onInit method to see what component bindings has.
vm.$onInit = function(){
console.log(vm.name);
}
The things which you were trying to do was totally doable till angular 1.5.X, but since AngularJS 1.6+ version they disabled prepopulating context of controller by introducing preAssignBindingsEnabled over $compileProvider. By default it is set to false. If you really want to see this working you could try to set the flag by below code(but I'd not recommend to use this). The main reason behind introducing this change is to make Angular and AngularJS API to look similar by design & architecture, eventually it will make one step closer to migration to Angular.
.config(function($compileProvider){
$compileProvider.preAssignBindingsEnabled(true);
})
Plunker

How to write HTML inside elements with Angular

I'm beginning with Angular, and just wanted to make some tests with Ajax, retrieving a document into my page. It works perfectly, but then a new challenge appeared: I want to be able to add HTML inside a DOM element.
Normally, one would do that from a directive and the templates thingy. But I want to do it at runtime, using a controller.
This is my code:
$http.get("import.html").then(function(response){
var element = document.createElement("div");
element.innerHTML = response.data;
angular.element("#div1").innerHTML(element);
});
Maybe I'm not using correctly "angular.element"? I tried using document.getElementByID, but it doesn't work either. I receive correctly the information from the file, but I just don't find a way I can compile that HTML in runtime.
Any help with this?
edit for showing my full code:
HTML:
<!DOCTYPE html>
<html ng-app="miApp">
<head>
<meta charset="UTF-8">
<script src="angular.js"></script>
<script src="mainmodule.js"></script>
<link rel="stylesheet" href="bootstrap/css/bootstrap.css">
</head>
<body ng-controller="controlador1">
<div id="div1" ng-bind-html="myHtml" style="top:50px;left:50px">
</div>
</body>
</html>
JS:
(tested all your examples, none worked for me, this is the last I used)
app.controller('controlador1', ["$scope", "$http", "$sce", "$compile", function($scope, $http, $sce, $compile) {
$http.get("import.html").then(function(response) {
var parent = angular.element("#div1");
var element = angular.element($sce.trustAsHtml(response.data);
$compile(element)($scope);
parent.append(element);
});
}]);
Usually, you want to compile your HTML if it contains any angular functionality at all (you need to declare '$compile' in your controller dependency list):
myApp.controller('myController', ['$scope', '$sce', '$compile'],
$scope, $sce, $compile) {
$http.get("test.html")
.then(function(response){
var parent = angular.element("#div1");
parent.append($compile(response.data) ($scope));
});
}]);
if you are hell-bent on useing innerHTML, note that angular.element("#div1") is the same as $("#div1") in jQuery. So you need to write angular.element("#div1")[0].innerHTML= ...
Here's a plnkr: http://plnkr.co/edit/p3TXhBppxXLAMwRzJSWF?p=preview
In this, I have made use of $sce. It's a dependency injection of AngularJS, where it treats the HTML as safe to bind. You can read about it in AngularJS site. Please find below code and working jsfiddle for the raised concern:
HTML:
<div ng-app="app" ng-controller="test">
<div>
This is onload HTML
</div>
<div ng-bind-html="dynamicHtml"></div>
</div>
JS
var app = angular.module('app', []);
app.controller('test', function ($scope, $sce) {
$scope.dynamicHtml = $sce.trustAsHtml("<div>This is dynamic HTML!!");
});
[Update]
HTML:
<div ng-bind-html="dynamicHtml"></div>`
JS:
$http.get("import.html").then(function (response) {
$scope.dynamicHtml = $sce.trustAsHtml(response.data); //Assuming 'response.data' has the HTML string
});
You are not using correctly angular. If you use angular, you don't harly ever have to use DOM selector.
Scope is binded with ng-model and {{}} on the view.
Now your answer. To print html on the view, you can do it in that way:
In controller:
$http.get("import.html").then(function(response){
$scope.html = $sce.trustAsHtml(response.data);
});
In view:
<div ng-bind-html="html"></div>
And more easy way:
<ng-include="'url/import.html'"><ng-include>
That's it!!!

AngularJS Manually Bootstrapping a module

My html...
<body id="main">
{{pageName}}
</body>
My JS:
angular.module('myApp',[])
.controller('myController', function($scope){
console.log('init');
$scope.pageName = 'My page';
});
angular.element(document).ready(function(){
angular.bootstrap(document.getElementById('main'), ['myApp']);
});
My Resulting HTML:
{{pageName}} instead of 'My Page'
I can do this
<body id="main" ng-controller="myController">
</body>
and it will start working. But, what is the point. Why do I necessarily have to use ng-controller ?
I hope I have made myself clear. Hoping someone would respond to this.
I think the reason is that you are setting pageName in myController but the div cannot use it as the controller is neither defined on it or its parent.
pageName should be set on $rootScope to make it work. You can define that at the run block of module like
angular.module('myApp',[]).run(function($rootScope) {
$rootScope.pageName='My Page';
});
This run block runs after angular has bootstrapped the application. See here
http://docs.angularjs.org/guide/module

dynamic routing AngularJS

I am trying to bind a route property to the src for ng-include:
config.js
$routeProvider.when('/services', {
templatePATH: '/views/services.html'
});
index.html
<html lang="en" ng-app="myApp" ng-controller="AppController">
<body>
<div ng-include src="{{page}}" class="container"></div>
</body>
</html>
controllers.js
controller('AppController', ['$scope','$route','$routeParams', function($scope, $route, $routeParams) {
var render = function(){
$scope.page = $route.current.templatePATH;
};
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
render();
});
}]).
Here's where I got the idea. What is strange is that the value of templateURL can be seen in the DOM on pageload where src is injected from the ng-include directive. Sadly however, this is not working.
Is it possible to achieve this kind of convention?
Oh your are just making a very small mistake please change your code to below
<div ng-include="page" class="container"></div>
More Detailed Answer :
When you use ng-include directive a watch is put on srcExp which is value of attr.ngInclude || attr.src so if you do {{page}} then you will be watching on the value of page not on page property so you have to put "page" without interpolated value so that it can watch directly on page instead of page string value

Categories