angularjs custom filter dynamic server call - javascript

I would like to call a server-side service when my filter is empty.
this is my HTML:
<html lang="en">
<head>
<meta charset="utf 8">
<title>test angular</title>
</head>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<body ng-app="app">
<h1 ng-app="app" ng-controller="HelloWorldCtrl">{{message}}</h1>
<p><input type="text" id="myfilter" ng-model="seachText"></p>
<div ng-app="app" id="search" ng-controller="serviceCall">
<ul>
<li ng-repeat="x in lau | myfilter:seachText">
{{ x.des }}
</li>
</ul>
</div>
and this is my code:
var app = angular.module("app", []);
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
});
app.filter('myfilter', [function($scope){
return function(input, param) {
if(!angular.isDefined(param)) param = '';
var ret = [];
angular.forEach(input, function(v){
var regx=new RegExp(param, 'gi');
if(regx.test(v.des)){
ret.push(v);
console.log("match!!");
}
});
if (!ret.length ){
$scope.serviceCall();
}
return ret;
};
}]);
I'm getting:
typeError: "$scope is undefined".
thanks in advance for the help.

$scope does not work in filter. Better inject a service, or pass the service function as another parameter to the filter:
return function(input, param, serviceCall) {
//...
serviceCall() // replaces $scope.serviceCall();
//...
}
Make sure you define serviceCall in the controller that calls the filter:
app.controller("serviceCall", function($scope, $http) {
var v=document.getElementById('search').value;
if (!v){v="Vigo";}
$scope.serviceCall = function() {
$http.get("http://127.0.0.1/KLAU.pl?search="+v+"&lim=10").then(function(response) {
$scope.lau = response.data;
});
};
$scope.serviceCall();
});
});
In HTML:
<li ng-repeat="x in lau | myfilter:seachText:serviceCall">

Related

Angular JS - Filter when value in specific key in one array also appears as value in specific key in another array

This questions comes from here
I want to make a filtering, so that I can show the values of colors.name just when they also appear as a value in cars.color
$scope.colors = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
$scope.cars=[ {"brand":"Ford","color":"blue", "seat":"pink"}
,{"brand":"Ferrari","color":"red", "seat":"pink"}
,{"brand":"Rolls","color":"blue","seat":"pink"}];
And then in the view:
<ul>
<li ng-repeat="n in colors | filter: filteredColors"> {{n}}
</li>
</ul>
The result should be
blue
red
I need the answer not to have ES6, and I need the filter to be in the controller. See plunkr here. Thanks in advance!
controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.colors = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
$scope.cars=[ {"brand":"Ford","color":"blue", "seat":"pink"}
,{"brand":"Ferrari","color":"red", "seat":"pink"}
,{"brand":"Rolls","color":"blue","seat":"pink"}];
$scope.filteredColors = function(color) {
var carsvar = $scope.cars;
for(var x = 0; x < carsvar.length; x++) {
if (color.name === carsvar[x].color) {
return true;
}
}
return false;
};
});
view:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.6.x" src="https://code.angularjs.org/1.6.6/angular.js" data-semver="1.6.6"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="color in colors | filter: filteredColors"> {{color.name}}
</li>
</ul>
</body>
</html>
You can use a custom filter:
app.filter('colorFilter', function(){
return function(val){
var colorsvar = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
var filtered = []
angular.forEach(val, function(key, value){
angular.forEach(colorsvar, function(key2, value2){
if(key.color === key2.name)
filtered.push(key)
})
})
return filtered;
}
})
And then on your html:
<li ng-repeat="n in cars | colorFilter"> {{n.color}}
Hope this helps.
As per your first question, there have some answers without using ES6. AngularJS - How to check that a specific key has a specific value in an array
So I thought you don't need to use any inbuilt function to do your logic.
Try to use with manual loop instead of using map or include bla bla bla.. Do Just like a normal JavaScript way in angularjs. Get this answer as a key. Take this answer as a key and do it with angular.filter().
var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope){
$scope.colors = [{"name":"blue","count":2},
{"name":"red","count":12},
{"name":"pink","count":5},
{"name":"yellow","count":2}];
$scope.cars=[ {"brand":"Ford","color":"blue"}
,{"brand":"Ferrari","color":"red"}
,{"brand":"Rolls","color":"blue"}];
$scope.filteredColors = function () {
var colorsvar = $scope.colors;
var carsvar = $scope.cars;
$scope.newValue = [];
for (var i = 0; i < colorsvar.length; i++) {
for (var j = 0; j < carsvar.length; j++) {
if (colorsvar[i].name == carsvar[j].color) {
if ($scope.newValue.indexOf(colorsvar[i].name) ==-1) {
$scope.newValue.push(colorsvar[i].name);
}
}
}
}
return $scope.newValue;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="n in filteredColors()"> {{n}}
</li>
</ul>
</div>

Pluralsight - AngularJS: Get Started

I follow the "AngularJS: Get Started" course from Plualsight, and I reach the Routing module, so I have some files in Plunker, on the course they can see on Preview page the title which is "Github Viewer" and a search bar. But I still get errors in console, and I do not know why, my code should be identical as their code.
So I have the following files :
app.js
(function() {
var app = angular.module('githubViewer', ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({redirectTo: "/main"});
});
}());
github.js
(function() {
var github = function($http) {
var getUser = function(username) {
return $http.get("https://api.github.com/users/" + username)
.then(function(response) {
return response.data;
});
};
var getRepo = function(user) {
return $http.get(user.repos_url)
.then(function(response) {
return response.data;
});
};
return {
getUser : getUser,
getRepo : getRepo
};
};
var module = angular.module("githubViewer");
module.factory("github", github);
}());
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.14" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script data-require="angular-route#*" data-semver="1.6.2" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script scr="app.js"></script>
<script src="MainController.js"></script>
<script src="github.js"></script>
</head>
<body>
<h1>Github Viewer</h1>
<div ng-view></div>
</body>
</html>
main.html
<div>
{{ countdown }}
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" ng-model="username" />
<input type="submit" value="Search" />
</form>
</div>
MainController.js
// Code goes here
(function() {
var app = angular.module("githubViewer");
var MainController = function($scope, $interval, $location) {
console.log("Atentie!")
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
//
};
$scope.username = "Angular";
$scope.countdown = 5;
startCountdown();
};
app.controller("MainController", MainController);
}());
userdetails.html
<div id="userDetails">
<h2>{{user.name}}</h2>
<img ng-src="{{user.avatar_url}}" title="{{user.name}}">
<div>
Order:
</div>
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | limitTo:10 | orderBy:repoSortOrder">
<td>{{repo.name}}</td>
<td>{{repo.stargazers_count | number }}</td>
<td>{{repo.language}}</td>
</tr>
</tbody>
</table>
And the style.css which is empty.
So at this point I should see in a separete window something like in the following picture and no errors in console.
But I se only the title, like in the following picture
and errors
Could someone help me to understand why isnt' work ?
Was some changes in AngularJS and the course isn't up to date ?
You made a typo
<script scr="app.js"></script>
should be
<script src="app.js"></script>
Also make sure that when using angularjs core api's, all the API should be off same version. Here you're using angularjs (ver. 1.3.12) & angular-route (ver. 1.6.2)
Change both to 1.6.2 or latest
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-route.js"></script>
Demo Here

No Inheritance is occuring in the angularJS code

This is an AngularJS inheritance code where the inheritance is applied in the functions but there is no output coming for this code.
custDetails and empPaycheck are the two functions where inheritance is applied but the code has some error which I am not been able to find.
<html lang="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Controller Inheritance</title>
<script src="angulaar.min.js"></script>
<script>
var app = angular.module("sample",
[]).run(["$rootScope",function($rootScope){
$rootScope.taxPe`enter code here`rcent = 30;
}]);
app.controller("custDetails", ["$scope",function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}]);
</script>
</head>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong>
Department.
<div controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
</html>
You should use $scope.$parent to access parent $scope variables in a child controller.
Also in your HTML code there's a typo where controller should be ng-controller.
Look at the following working example.
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.$parent.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.$parent.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div>
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
There is error in your module run block near $rootScope.taxPe;
You are using controller attribute instead of ng-controller.
Here is a working code snippet:
var app = angular.module("sample", []).run(["$rootScope", function($rootScope) {
$rootScope.taxPercent = 30;
}]);
app.controller("custDetails", ["$scope", function($scope) {
$scope.Name = "Dipanshu";
$scope.Sal = 45000;
$scope.Dept = "Testing";
}]);
app.controller("empPayCheck", ["$scope", "$rootScope",
function($scope, $rootScope) {
$scope.getTaxes = function() {
return $scope.Sal * $rootScope.taxPercent / 100;
};
$scope.getNet = function() {
return $scope.Sal - $scope.getTaxes();
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="sample">
<div ng-controller="custDetails">
Employee Details of {{Name}}
<div ng-controller="custDetails">
{{Name}} earns {{Sal}} rs and is in <strong>{{Dept}}</strong> Department.
<div ng-controller="empPayCheck">
Tax: {{getTaxes()}}
<br> Net Amount: {{getNet()}}
</div>
</div>
</div>
</body>
P.S.: Personally I would not recommend using $rootScope and scope inheritance, you can use services to share data between controllers. Also would suggest you looking into component API that comes in v1.5+.

angular expression in html view rendering same data for different expressions

Angular expressions on one of my view are rendering same data on screen
it would show : hello - hello ( for different expressions {{a}}, {{b}} )
There is cleary different data binded to 'a' and 'b' variables in controller.
html view :
{{ a | json }} - {{ b | json }}
angular controller:
app.controller('myctrl', function($scope, myservice) {
var self = this;
self.getA = function() {
$scope.a = 'hello';
}
self.getB = function() {
$scope.b = 'hey';
}
self.getA(); //call on controller startup
self.getB();
});
Your code works without any issue,
Make sure you are doing the following.
DEMO
var app = angular.module('myctrl',[]);
app.controller('myctrl', function($scope) {
var self = this;
self.getA = function() {
$scope.a = 'hello';
}
self.getB = function() {
$scope.b = 'hey';
}
self.getA(); //call on controller startup
self.getB();
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dashboard</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body >
<div ng-app="myctrl" >
<div ng-controller="myctrl as ctrl" >
{{ a }} - {{ b }}
</div>
</div>
</body>
</html>

AngularJS Unknown Provider (filterProvider) error

The two script statements below work independently however when they are combined it causes Error: [$injector:unpr] Unknown provider: searchNameFilterProvider <- searchNameFilter Can anyone explain why this occurs?
1st segement
Find Person: <input type="text" ng-model="myName">
<ul ng-init="people = ['Diarmuid','Aine','Dave','Declan']">
<li ng-repeat="person in people | filter:myName">{{ person | searchName}}</li>
</ul>
<script>
var app = angular.module('myApp',[]);
app.filter('searchName',function(){
return function (input){
return input + '!';
}
})
</script>
2nd segement
<div ng-controller="myCtrl">
<button ng-click="myFunc()">Hello World Button</button>
</div>
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl',function ($scope) {
$scope.myFunc = function () {
console.log('Hello world!');
};
});
</script>
<div ng-app="myApp">
<script src="Scripts/Angular.js" type="text/javascript"></script>
Find Person:
<input type="text" ng-model="myName">
<ul ng-init="people = ['Diarmuid','Aine','Dave','Declan']">
<li ng-repeat="person in people | filter:myName">{{ person | searchName}}</li>
</ul>
<script>
var app = angular.module('myApp', []);
app.filter('searchName', function () {
return function (input) {
return input + '!';
};
});
</script>
<div ng-controller="myCtrl">
<button ng-click="myFunc()">
Hello World Button</button>
</div>
<script>
var app = angular.module('myApp');
app.controller('myCtrl', function ($scope) {
$scope.myFunc = function () {
console.log('Hello world!');
};
});
</script>
There should only be a single module intialization in your code. Fixing the repeated intialization solves the problem.
var app = angular.module('myApp', []);
Here is the documentation from the AngularJS docs.
"Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module"
You could read more about the modules here. AngularJS Modules
var app = angular.module('myApp', []);
app.filter('searchName', function() {
return function(input) {
return input + '!';
}
});
app.controller('myCtrl', function($scope) {
$scope.myFunc = function() {
console.log('Hello world!');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
Find Person:
<input type="text" ng-model="myName">
<ul ng-init="people = ['Diarmuid','Aine','Dave','Declan']">
<li ng-repeat="person in people | filter:myName">{{ person | searchName}}</li>
</ul>
<div ng-controller="myCtrl">
<button ng-click="myFunc()">Hello World Button</button>
</div>
</div>

Categories

Resources