How to render html with AngularJS templates - javascript

This is my template:
<div class="span12">
<ng:view></ng:view>
</div>
and this is my view template:
<h1>{{stuff.title}}</h1>
{{stuff.content}}
I am getting the content as html and I want to display that in a view, but all I am getting is raw html code. How can I render that HTML?

Use-
<span ng-bind-html="myContent"></span>
You need to tell angular to not escape it.

To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>

In angular 4+ we can use innerHTML property instead of ng-bind-html.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';

You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe
Let's take an example with asynchroniously loading Eventbrite login button
In your controller:
someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin',
function($scope, $sce, eventbriteLogin) {
eventbriteLogin.fetchButton(function(data){
$scope.buttonLogin = $sce.trustAsHtml(data);
});
}]);
In your view just add:
<span ng-bind-html="buttonLogin"></span>
In your services:
someAppServices.factory('eventbriteLogin', function($resource){
return {
fetchButton: function(callback){
Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
callback(widget_html);
})
}
}
});

So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:
<html>
<body ng-app="yourApp">
<div class="span12">
<div ng-view=""></div>
</div>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
Then yourView.html could just be:
<div>
<h1>{{ stuff.h1 }}</h1>
<p>{{ stuff.content }}</p>
</div>
scripts.js could have your controller with data $scope'd to it.
angular.module('yourApp')
.controller('YourCtrl', function ($scope) {
$scope.stuff = {
'h1':'Title',
'content':"A paragraph..."
};
});
Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)
angular.module('yourApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/yourView.html',
controller: 'YourCtrl'
});
});
I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

Related

Can't access controller properties in view with UI router and 'controller as' syntax

I am using ui-router for my routing, and am going to be using nested scopes and therefore want to be using the 'controller as' syntax. However, I can't work out the correct syntax / combinations to access the controller object properties in my view.
app.js (sets up routing)
(function() {
angular
.module('ICP_App', ['ui.router', 'satellizer', 'ngMaterial', 'ngMessages', 'xeditable'])
.config(function($stateProvider, $urlRouterProvider, $authProvider) {
$urlRouterProvider.otherwise('dashboard');
$stateProvider
.state('clients', {
url: '/clients',
templateUrl: '../partials/clients-index.html',
controller: 'ClientsController as ClientsCtrl'
})
// more routes here...
})();
ClientsController.js
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
var vm = this;
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
});
})();
index.html
<body ng-app="ICP_App" ng-cloak>
<!-- sidebar, header etc -->
<div ui-view></div> <!-- pull in view -->
</body>
Finally, clients-index.html partial
<div class="content">
<div class="pane" ng-repeat="client in clients">
{{ client.name }}
</div>
</div>
I have also tried client in vm.clients, to no avail.
Is there a problem with my controller as syntax? As I am using controller as in my ui-router code, yet not again when creating my controller. If I use controller as again in my controller, it errors (Argument ClientsController is not a).
I should point out that console logging vm.clients does give me the data in the console, I just can't seem to access it in my view.
Thanks in advance.
Modify your ClientsController as follow
(function() {
angular.module('ICP_App')
.controller('ClientsController', function($http) {
var vm=this;
$http.get('http://api.icp.sic.com/clients')
.success(function(clients) {
vm.clients = clients.data;
console.log(vm.clients);
})
.error(function(error) {
// handle here
})
}); })();
Modify client-index.html as following
<div class="content">
<div class="pane" ng-repeat="client in ClientsCtrl.clients">
{{ client.name }}
</div>
Below link will help you to understand controller as syntax more deeply
https://toddmotto.com/digging-into-angulars-controller-as-syntax/

Calling controller from function and passing it a URL-encoded parameter

I am developing a CRUD interface for a Rest service. Currently, I could manage to get the list of teams in the system.
What I like to do is to show details for the when I click the show link. Currently clicking on the link calls a function (not yet implemented) that is supposed to load the details part into the ng-view. The function should pass a parameter to the ViewTeamController which will subsequently invoke the Rest service and give the result to a $scope variable.
I am not sure about how to call the ViewTeamController possibly using a URL encoded parameter from the showTeam() function. And I would also like to know how to read the URL-encoded parameter inside the ViewTeamController.
Thanks in advance.
<!doctype html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular-route.min.js"></script>
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
});
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
mainApp.controller('AddTeamController', function($scope) {
});
mainApp.controller('ViewTeamController', function($scope) {
});
</script>
</head>
<body>
<div ng-app = "teamApp" ng-controller="teamController">
<a ng-click="newTeam()">new</a>
<div ng-repeat="team in teams" >
Name: {{team.name}}
<br />
Description: {{team.description}}
<br />
<a ng-click="showTeam(team.id)">show</a>
</div>
<div ng-view></div>
<script type = "text/ng-template" id = "addTeam.htm">
<h2> Add Team </h2>
To be implemented later.
</script>
<script type = "text/ng-template" id = "viewTeam.htm">
Name: {{team.name}}
Description: {{team.description}}
</script>
</div>
</body>
</html>
Your controller functions can get access to route parameters via the AngularJS $routeParams service like this:
mainApp.controller('ViewTeamController', function($scope, $routeParams) {
$scope.param = $routeParams.param; // will hold your encoded params
});
Considering you are passing the parameters as something like this in your URL,
/viewTeam/23535t4645645g4t4
Now your $scope.param will hold 23535t4645645g4t4

AngularJS get parameters from Laravel

I don't know how to pass a variable from home.blade.php of Laravel to my Controller.js of AngularJS.
LARAVEL:
I have a home.blade.php with a variable searchid:
#extends('layouts.default')
#section('content')
<div class="row" ng-app="app">
{{ $searchid }}
<post-controller></post-controller>
</div>
#stop
This variable is send by controller of Laravel:
class SearchController extends BaseController {
public function makeSearch($searchid)
{
return View::make('pages.search')->with('searchid', $searchid);
}
}
ANGULARJS:
I need to pass this variable to AngularJS controller.
I have a directive file like this:
app.directive('postController', function()
{
return {
restrict: 'E',
templateUrl: 'templates/search.html'
}
});
And controller file like this:
app.controller('SearchController', ['$scope', function($scope, $routeParams)
{
console.log($routeParams.search);
$scope.param = $routeParams.search;
}]);
I don't know how to pass this variable search to my controller.js.
There's a nice package that does nearly all the work for you. PHP-Vars-To-Js-Transformer
However the basic principle is just passing variables to javascript by creating a <script> tag in your view and defining javascript variables. Here's an example:
<script type="text/javascript">
var searchId = {{ $searchId }};
</script>
Attention depending on the data type of your variable you'll have to use quotes around it or maybe even serialize it with json.

Toggle visibility of a ng-include depending on route

I have the following configuration:
$routeProvider
.when('/cars', { templateUrl: 'app/cars/index.html', controller: 'CarsCtrl', reloadOnSearch: false })
.when('/bikes', { templateUrl: 'app/bikes/index.html', controller: 'BikesCtrl', reloadOnSearch: false });
and somewhere in my root index.html there is a:
Cars
Bikes
<div ng-view></div>
Now, I want both views loaded and generated in the DOM at the same time, and show one of them depending on the route/URL.
Something like the following (not actual working code, just to give you an idea).
app.js:
$routeProvider
.when('/cars', { controller: 'CarsCtrl', reloadOnSearch: false })
.when('/bikes', { controller: 'BikesCtrl', reloadOnSearch: false });
root index.html:
Cars
Bikes
<div ng-include="'app/cars/index.html'" ng-show="carsVisible"></div>
<div ng-include="'app/bikes/index.html'" ng-show="bikesVisible"></div>
UPDATE: I know that ng-view kind of does this, but the difference, if subtle, exists. I want the html of each view to be generated once and stay in the DOM at all times.
I created a single RouteCtrl to load all of your views via ng-include. ng-view is not used. I inlined the templates. The templates could contain their own ng-controller directives to pull in specific controllers.
<body ng-controller="RouteCtrl">
Cars
Bikes
<div ng-controller="RouteCtrl">
<div ng-include="'/cars.html'" ng-show="carsVisible"></div>
<div ng-include="'/bikes.html'" ng-show="bikesVisible"></div>
</div>
<script type="text/ng-template" id="/cars.html">
Cars template.
</script>
<script type="text/ng-template" id="/bikes.html">
Bikes template.
</script>
$routeProvider is still configured, but no template or controller is specified, causing the RouteCtrl to always be active. That controller listens for the $routeChangeSuccess event and manipulates the ng-show properties accordingly.
app.config(function($routeProvider) {
$routeProvider
.when('/cars', {} )
.when('/bikes', {})
});
app.controller('RouteCtrl', function($scope, $route, $location) {
$scope.$on('$routeChangeSuccess', function() {
var path = $location.path();
console.log(path);
$scope.carsVisible = false;
$scope.bikesVisible = false;
if(path === '/cars') {
$scope.carsVisible = true;
} else if(path === '/bikes') {
$scope.bikesVisible = true;
}
});
});
Plunker
The idea for this solution is from #Andy.
I found another way, which I think is the simplest, quickest and most manageable:
How to set bootstrap navbar active class with Angular JS?
Which is:
Use ng-controller to run a single controller outside of the ng-view:
<div class="collapse navbar-collapse" ng-controller="HeaderController">
<ul class="nav navbar-nav">
<li ng-class="{ active: isActive('/')}">Home</li>
<li ng-class="{ active: isActive('/dogs')}">Dogs</li>
<li ng-class="{ active: isActive('/cats')}">Cats</li>
</ul>
</div>
<div ng-view></div>
and include in controllers.js:
function HeaderController($scope, $location)
{
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
}
Instead of using ng-include, you should use ng-view;
This will display the content of either app/cars/index.html or app/bikes/index.html
Cars
Bikes
<div ng-view></div>
See the Template section from http://docs.angularjs.org/tutorial/step_07
Use a service with a show directive:
<div ng-show="myService.isActive('/')">Show this when at default route</div>
<div ng-show="myService.isActive('/cars')">Show this when at cars</div>
Service:
myApp.factory('MyService',
function ($location) {
return {
isActive: function (path) {
return (($location.path() == path));
}
}
}
);
App.js:
// this is run after angular is instantiated and bootstrapped
myApp.run(function ($rootScope, myService) {
$rootScope.breadcrumbService = MyService;
});

AngularJS Controller depending on URL parameter

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.
I start to learn AngularJS and I have a very simple question :
Depending on ID contained in URL, I would like to display different BD record.
...
<div ng-app=MyApp>
<div ng-controller="MyCtrl">
{{ record }}
</div>
</div>
...
My Javascript file :
var MyApp = angular.module("MyApp",[]);
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/get/:productId', {
controller: 'MyCtrl'
});
}])
MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
function($scope,$routeParams,$http) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
}])
I tried to use $routeProvider and $routeParams without success.
Thank you in advance,
Bill
you need 2 things , the $routeParams injected in your controller and create a valid route with the get method
MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
function($scope,$http,$routeParams) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
};

Categories

Resources