Adding a filter in angularjs - angularjs

I am new with angularjs and I am trying to create a filter that remove spaces from a string.
removeSpaces.js
angular.module('filters.stringUtils', [])
.filter('removeSpaces', [function() {
return function(string) {
if (!angular.isString(string)) {
return string;
}
return string.replace(/[\s]/g, '');
};
}])
home.html
<div ng-controller="ItemController">
<p ng-repeat="item in items">
{{ item.item_name }}
</p>
itemcontroller.js
angular.module('myApp').controller('ItemController', [
'$scope', 'Services', '$http','removeSpaces', function($scope, Services, $http,removeSpaces) {
$http.defaults.headers.common['Accept'] = 'application/json';
return $scope.services = Services.query();
}
]);
I get this error:
Unknown provider: removeSpacesFilterProvider <- removeSpacesFilter

In your app you have to use the module for you app.
So do this and it should work
angular.module('myApp', ['filters.stringUtils'])

Related

ionic + anguular ng-bind-html is not working

I have fetched json webservice one of its field contain HTML tags
actually web service has < & > my code looks like
angular.module('starter.controllers', ['ionic','ngSanitize'])
.controller('DashCtrl', function($scope) {})
.controller('DetailCtrl', ['$sce','$scope', '$stateParams','Chats',function($sce,$scope, $stateParams, Chats) {
$scope.exe = Chats.detail($stateParams.exeId,$stateParams.sub_exeId);
$scope.renderHtml = function(html_code)
{
return $sce.trustAsHtml(html_code);
};
}])
//also tried the following filter
.filter('to_trusted', ['$sce', function($sce){
return function(text) {
return $sce.trustAsHtml(text);
};
}])
at my view I tried the following variations
<p ng-bind-html="exe.tips.replace('<','<').replace('>','>') | to_trusted"></p>
<p ng-bind-html="exe.tips | to_trusted"></p>
<p ng-bind-html="exe.tips"></p>
<p ng-bind-html="renderHtml(exe.tips)"></p>
and tried many other thing but still getting rendered the HTML
at view source it is like this <p>"<ol><li>text</li>....

Parsing Json Array in AngularJS

Iam newbie in angularjs.How to display the json in html using angularjs.Below is the code
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope, $http) {
$http.get("http://localhost:8080/xyz").then(function (response) {
});
});
Reponse is :
[
{
"city": "animal"
},
{
"city": "bird"
}
]
In your controller you should assign your json to a scope:
app.controller('myctrl', function($scope, $http) {
$scope.myArray = [];
$http.get("http://localhost:8080/xyz").then(function (response) {
$scope.myArray = response;
});
});
Then in your view, you can do something like:
<div ng-controller="myctrl">
<ul ng-repeat="obj in myArray">
<li>{{obj.city}}</li>
</ul>
</div>
use ng-repeat like this.
<div ng-repeat="t in test">
<span>{{t.city}}</span>
</div>
plunker here
Use the following code this might help you.
myArray = JSON.parse(response);
for ( var index in myArray ) {
var singleObject = myArray[index];
var keys = Object.keys[singleObject];
for ( var j in keys ) {
console.log("Value of key"+j+"is"+keys[j]+"in Object"+index);
}
}
Here response is a string value.
Try this
Where Records is like this..
{"records":[{"ID":"235","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_02a29.jpg","ImageName":"1.jpg"},{"ID":"236","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_f0f59.jpg","ImageName":"253.jpg"},{"ID":"239","user_id":"2","project_id":"186","project_cid":"1997319193267363957","imagePath":"media/pano/sv_6536f.jpg","ImageName":"PANOCLOUD_meta.jpg"},{"ID":"240","user_id":"2","project_id":"186","project_cid":"6736594884768838469","imagePath":"media/pano/sv_898ca.jpg","ImageName":"Boscolo Hotel Budapest.jpg"}]}
$http.get("moderatorData.php").then(function (response) {
$scope.panoramas = response.data.records;
});
Then print using like this
<li class="align" ng-repeat="pano in panoramas>
<img ng-src="{{pano.imagePath}}" style="height: 90px;" />
</li>

Restangular / Json-ld | I can get the data, but I can't show them

I'm new in Angular and need your help.
With my team, we made a PHP REST API in Symfony that we want to connect to an Angular client.
I already have the Angular app..
I can see in my XHR requests that i actually get the entities and their properties (users).
But in my view, i tried some {{ user.name }} with ng-repeat but it dosen't show anything.
Datas are sent in Json-ld and we use Restangular to read them.
Here some code :
app.js :
angular
.module('frontApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'restangular'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'AboutCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.config(['RestangularProvider', function (RestangularProvider) {
// The URL of the API endpoint
RestangularProvider.setBaseUrl('http://localhost:8000');
// JSON-LD #id support
RestangularProvider.setRestangularFields({
id: '#id'
});
RestangularProvider.setSelfLinkAbsoluteUrl(false);
RestangularProvider.setResponseExtractor(function(response) {
var newResponse = response;
if (angular.isArray(response)) {
angular.forEach(newResponse, function(value, key) {
newResponse[key].originalElement = angular.copy(value);
});
} else {
newResponse.originalElement = angular.copy(response);
}
return newResponse;
});
// Hydra collections support
RestangularProvider.addResponseInterceptor(function (data, operation) {
// Remove trailing slash to make Restangular working
function populateHref(data) {
if (data['#id']) {
data.href = data['#id'].substring(1);
}
}
// Populate href property for the collection
populateHref(data);
if ('getList' === operation) {
var collectionResponse = data['hydra:member'];
collectionResponse.metadata = {};
// Put metadata in a property of the collection
angular.forEach(data, function (value, key) {
if ('hydra:member' !== key) {
collectionResponse.metadata[key] = value;
}
});
// Populate href property for all elements of the collection
angular.forEach(collectionResponse, function (value) {
populateHref(value);
});
return collectionResponse;
}
return data;
});
}])
;
main.js :
angular.module('frontApp')
.controller('MainCtrl', function ($scope, Restangular) {
$scope.ami1 = Restangular.one('amis',1).get();
$scope.test ='Test';
var amis = Restangular.all('amis');
amis.getList().then(function (ami) {
$scope.ami = ami;
});
});
main.html:
<div class="jumbotron">
<p>Liste d'amis :</p>
{{ ami1.nom }}
{{ test }}
<div ng-repeat="ami in amis" id="{{ ami['#id'] }}" class="row marketing">
<h1>{{ ami.nom }}</h1>
<h2>{{ ami.prenom }}</h2>
<h3>{{ ami.id }}</h3>
</div>
chrome console
Thanks for helping!
I found by myself, here is the code :
<div ng-repeat="ami in amis" id="{{ ami['#id'] }}" class="row marketing">
<h1>Nom: {{ ami.nom }}</h1>
<h2>Prenom: {{ ami.prenom }}</h2>
<h3>Date de naissance: {{ ami.dateNaissance }}</h3>
<h4>Telephone(s): </h4>
<div ng-repeat="telephone in ami.telephones" id="{{ telephone['#id'] }}">
{{ telephones[$index].numero }}
</div>
</div>
in your controller ...
$scope.amis = Restangular.all('amis').getList();
if that doesn't work ...
Restangular.all('amis').getList().then(function(response) {
$scope.amis=response;
}).catch(function(error) {
console.log(error);
})
Ok now i have another issue.
I have all of my 'ami' and their properties so it's really great, but my 'ami' have many 'telephone' ids in it.
What i try to do is to have my 'ami' 'numero' from 'telephone' with this telephone id.
i can list all of my 'amis' with telephon id in it, and all of my 'telephones' with the numeros in it.
Thanks angain :)

How should you access controller functions from other modules

I am having a hard time understanding how Modules should interact with each other in Angularjs. I would like to break the application into nice small modules, but I cannot seem to find the correct way to have these modules interact with each other.
JSFiddle:
http://jsfiddle.net/jwest80/o5o3sr8q/4/
The code shows a breadcrumb I would like to have at the top of the page. The BreadCrumb is in its own module 'bread' and included inside a parent module 'ngFSCH'.
There is a list outside BreadCrumb controller section whose actions should add breadcrumbs. However, I do not understand the correct way to access this addCrumb function. I can only make it work if it is called from inside the breadcrumb controller section in the markup.
Markup:
<div ng-app="ngFSCH">
<section ng-controller="BreadCrumbsCtrl">
<span ng-repeat="crumb in crumbs" class="breadcrumbs">
<span ng-hide="isLast($index)" ng-click="selectCrumb($index)">{{crumb.text}} > </span>
<span ng-show="isLast($index)">{{crumb.text}}</span>
</span>
</section>
<section>
<h4>Add Some Crumbs</h4>
<ul>
<li>Company</li>
<li>Department</li>
<li>User</li>
</ul>
</section>
</div>
Script:
var ngFSCH = angular.module('ngFSCH', ['bread']);
(function () {
var app = angular.module('bread', []);
app.controller('BreadCrumbsCtrl', ['$scope', '$log', function ($scope, $log) {
$scope.crumbs = [{ text: "Crumb 1", url: "url1" }, { text: "Crumb 2", url: "url2" }];
$scope.isLast = function(index) {
return index === $scope.crumbs.length-1;
}
$scope.addCrumb = function (newCrumb) {
$scope.crumbs.push({ text: newCrumb, url: "TestURL" });
}
$scope.selectCrumb = function (index) {
$log.info($scope.crumbs[index].url);
$scope.crumbs = $scope.crumbs.slice(0, index + 1);
}
}]);
})();
I would encapsulate the bread crumb functionality in a service and create a controller for the section with the links (that add the breadcrumbs). The new controller can then use the service to add and remove crumbs from the array. You can also add the crumbs array into a value.. Your controllers can then expose the add and select features to the tiny portions of html they control without polluting other sections of your page.
Here is the result. Hope it helps!
JSFiddle
Here is the code:
var app = angular.module('bread', []);
app.value('crumbs', [
{ text: "Crumb 1", url: "url1" },
{ text: "Crumb 2", url: "url2" }
]);
app.factory("BreadCrumbsService", ['$log', 'crumbs', function ($log, crumbs) {
var service = {
getCrumbs: getCrumbs,
addCrumb: addCrumb,
selectCrumb: selectCrumb
};
return service;
//I did not add a set crumbs because you can set it directly.
function getCrumbs(){
return crumbs;
}
function addCrumb(newCrumb) {
crumbs.push({
text: newCrumb,
url: "TestURL"
});
}
function selectCrumb(index) {
$log.info(crumbs[index].url);
crumbs = crumbs.slice(0, index + 1);
}
}]);
app.controller('BreadCrumbsCtrl', ['$scope', 'BreadCrumbsService', function ($scope, BreadCrumbsService){
$scope.crumbs = BreadCrumbsService.getCrumbs;
$scope.selectCrumb = BreadCrumbsService.selectCrumb;
$scope.isLast = function (index) {
return index === BreadCrumbsService.getCrumbs().length - 1;
}
}]);
app.controller('AddLinksCtrl', ['$scope', 'BreadCrumbsService', function ($scope, BreadCrumbsService) {
$scope.addCrumb = BreadCrumbsService.addCrumb;
}]);
Here is the links section with the new controller:
<section ng-controller="AddLinksCtrl">
<h4>Add Some Crumbs</h4>
<ul>
<li>Company</li>
<li>Department</li>
<li>User</li>
</ul>
</section>
That is intended because you are working within the scope of the controller. How about moving the ng-controller directive to the containing div where ng-app is?
<div ng-app="ngFSCH" ng-controller="BreadCrumbsCtrl">

How to refresh an ng-repeat list when the backing model has been updated via ng-click?

I'm rather new to AngularJS so I presume this is going to be something about confusing scope.
I'm trying to get a ng-repeat list watching a service on the scope to update when I push a new item to the service backing model from a ng-click anchor link.
An example failing fiddle is here: http://jsfiddle.net/znFwY/
JS:
'use strict';
angular.module('myApp', [])
.factory('Order', function () {
return {
packages: {
theList: [],
list: function () {
return this.theList;
},
push: function (p) {
if (p === undefined || !!this.theList[p.title]) return;
this.theList[p.title] = p;
console.log('pushed ' + p.title);
},
contains: function (p) {
return !!this.theList[p.title];
},
print: function () {
console.log(this.theList);
}
}
}
})
.controller('AppCtrl', function ($scope, $http, $location, Order) {
$scope.order = Order;
$scope.data = {
packages: [
{title: 'one'},
{title: 'two'},
{title: 'three'},
]
};
})
;
HTML:
<div ng-app="myApp">
<div ng-controller="AppCtrl">
<ul id="package-list">
<li ng-repeat="package in data.packages | orderBy:package.order">
<a ng-click="order.packages.push(package)" ng-class="{selected: order.packages.contains(package)}">{{package.title}}</a>
</li>
</ul>
<ul id="basket-list">
<li ng-repeat="package in order.packages.list() | orderBy:package.order"> {{package.title}}</li>
</ul>
<a ng-click="order.packages.print()">print list</a>
</div>
</div>
Thanks

Resources