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

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

Related

Why can't I use AngularJS to load a JSON file and angular route in the same page?

I'm not a native speaker, sorry for my unclear question.
I'm trying to use AngularJS to read a JSON file. I did it but when I use angular route in the same page, the angular route didn't run. Then I figured out that I can only use one function in 1 page. For more clearly, here is my code:
In home.html:
<!DOCTYPE html>
<html ng-app="UpStore">
<head>
</head>
<body ng-controller="ProductController">
<div ng-view> </div>
<!--Javascript-->
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-
route.js"></script>
<script src="js/app.js"></script>
<script>
var app = angular.module("UpStore", [])
app.controller("ProductController", function ($scope, $http) {
$http({
method: "GET",
url: "productdata.json"
}).then(function mySucces(respone) {
$scope.products = respone.data
}, function myError(respone) {
$scope.dataError = respone.statusText
}
)
})
</script>
</body>
</html>
app.js:
var App = angular.module('UpStore', []);
App.controller('ProductController', function ($scope) {
});
var App = angular.module('UpStore', ['ngRoute']);
App.config(function ($routeProvider) {
$routeProvider
.when('/men', {
templateUrl: 'men.html',
})
.when('/product', {
templateUrl: 'product.html',
}).
otherwise({
redirectTo: 'men'
});
});
App.controller('ProductController', function ($scope) {
});
In men.html:
<div ng-repeat="pd in products">
<p>{{pd.ID}}</p>
<p><img src="image/{{pd.Image}}" /></p>
</div>
I also has one more question. In page men.html, I have several products, each product has an ID. I have a page product.html to show the product details. What I want to do is when I click on an image of a product in page men.html. The URL to the product.html would be like product.html/productid. I know that $routeParams can solve my problem, but I don't know how to write the code.
I really need some help because I've been struggling with these 2 problems for hours. Thanks in advance.
You are continuously overwriting the previously defined modules.
As you have already defined the module UpStore in the app.js
//Define it only once
var App = angular.module('UpStore', ['ngRoute']);
You need to get the reference of it in the script block and use.
//Get the reference to existing module
var app = angular.module("UpStore");
//Use it
app.controller(.......)
Additionally: Note always use same version of angular.js and angular-route.js library

AngularJS: Same template is used by two different URL, I want to change some parts of view when on other URL

For example I have this input button:
<input type="button" class="blue-button pull-right" value="{{gb.gebruikerToevoegenText}} toevoegen" ng-click="gebruikers.addGebruiker()"/>
In the controller I am trying to achieve this through this logic:
vm.gebruikerToevoegenText = $location.path() == '/gebruikers' ? "Super User" : "Gebruiker";
But this guides me to same url for both views i.e. /gebruikers
I want its value to be different when the URL is /gebruikers/:id?/:naam?', below is the route definition:
$routeProvider.when('/gebruikers/:id?/:naam?', {
templateUrl: 'gebruikers.html',
controller: 'gebruikersController as gebruikers',
resolve: {
authentication: ['fwgAuthService', function (fwgAuthService) {
return fwgAuthService.login();
}]
}
});
$routeProvider.when('/gebruiker/:licentieHouderId/:id?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikerController as vm',
resolve: {
authentication: ['fwgAuthService', function (fwgAuthService) {
return fwgAuthService.login();
}]
}
});
I want to change user rights as well on this URL , but only if I know how to manipulate the view based on URL, I do not want to change the template, other wise it is going to be lots of copy and paste.
You'll have to change the template anyways. Please don't pollute the rootScope for this; you can use ng-if or ng-show/hide (as already suggested). Just add an isAuthorized() function to your controller and set a flag if the url matches a certain pattern. Moreover I would alter the controllerAs name to the same name for both path in order to make templating easier.
I checked the url by using the following function in the controller thanks for helping out:
vm.gebruikerToevoegenText = $routeParams.id ? "Super User" : "Gebruiker";
Index.html
<!doctype html>
<html ng-app="routerApp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
<script>
var routerApp = angular.module('routerApp', ['ui.router', 'ngRoute']);
routerApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/gebruikers/:id?/:naam?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikersController'
}).
when('/gebruiker/:licentieHouderId/:id?', {
templateUrl: 'gebruiker.html',
controller: 'gebruikerController'
}).
otherwise({
redirectTo: '/gebruikers/:id?/:naam?'
});
}]);
routerApp.controller('gebruikersController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.toevoegen = "Pratapsss";
}]);
routerApp.controller('gebruikerController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.toevoegen = "Pratap";
}]);
</script>
</head>
<body>
<div ng-view></div>
</body>
</html>
gebruiker.html
<div>
<input type="button" class="blue-button pull-right" ng-value="toevoegen" ng-click="gebruikers.addGebruiker()"/>
</div>

UI-Router for item list Angularjs

I'm facing some problems with my simple code (study), i really need some help to fix this.
First of all i have a php file who provides a json.
app.php
<?php
$dbh = new PDO('mysql:host=localhost;dbname=caio', 'root', '');
$a = $dbh->query("SELECT * FROM usuario");
$b = json_encode($a->fetchAll(PDO::FETCH_ASSOC));
echo $b;
?>
It's a simple json with id, name and surname
Also i have a Js file to get this.
app.js
var meuApp = angular.module('meuApp', ['ui.router']);
meuApp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
templateUrl: 'uDetail.html'
});
});
meuApp.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('app.php')
.success(function(data) {
$scope.usuarios = data;
console.log(data);
//just checking in the console...
var id = data[0].id
console.log(id);
var nome = data[0].nome
console.log(nome);
});
}]);
and finally my html file
<html ng-app="meuApp" lang="pt">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail">{{usuario.nome}}</a>
</li>
</ul>
</div>
</body>
If i want to show, ok the code is working, but i want to click in each name and then the template shows me the id, name and surname of this "person". That's my problem.
Thank you guys.
Here you need to pass person object from one state to another state.
For that you can use params attribute of ui-router. When you click any perticular person at that time you need to pass id also while routing from one state to another because you already configure in url "/usuarios/{id}".
ui-router will match that property from params and will set in url.
Now you can successfully pass clicked object from one state to another. Get that object with $stateParams service of ui-router in controller of usuarios.detail state so that you can display in uDetail.html
meuApp.config(function($stateProvider, $urlRouterProvider,$stateParams){
$stateProvider
.state('usuarios.detail', {
url: "/usuarios/{id}",
params: {
id: null,
person:null
},
templateUrl: 'uDetail.html',
controller: function($scope, $stateParams) {
$scope.portfolioId = $stateParams.id;
$scope.person = $stateParams.person;
console.log("State parameters " + JSON.stringify($stateParams));
}
});
});
and in your template where you are showing the list.
<ul>
<li ng-repeat="usuario in usuarios">
<a ui-sref="usuarios.detail({ id:usuario.id,person:usuario})">{{usuario.nome}}</a>
</li>
</ul>
See above code which I gave for your reference.
You can see this Demo for in detail idea of ui-router.
You need some minor changes in order to get your code working, check the files bellow:
index.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="userCtrl">
<ul>
<li ng-repeat="user in users">
<a ui-sref="users.detail({id: user.id, user: user})">{{user.name}}</a>
</li>
</ul>
</div>
<div ui-view></div>
</body>
app.js
var app = angular.module('app', ['ui.router']);
app.config(function($stateProvider) {
$stateProvider
.state('users', {
abstract: true,
url: 'users',
template: '<div ui-view></div>'
})
.state('users.detail', {
url: '/:id',
templateUrl: 'users.detail.html',
params: {
user: null
},
controller: function($scope, $stateParams) {
$scope.user = $stateParams.user;
}
});
});
app.controller('userCtrl', ['$scope', '$http',
function($scope, $http) {
// replace this with your service call
$scope.users = [{
id: 1,
name: 'john',
surname: 'doe'
}, {
id: 2,
name: 'mary',
surname: 'poppins'
}];
}
]);
user.detail.html
<fieldset>
<div>
<label>id: </label> {{user.id}}
</div>
<div>
<label>name: </label> {{user.name}}
</div>
<div>
<label>surname: </label> {{user.surname}}
</div>
</fieldset>

How to render html with AngularJS templates

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

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