Why custom unique is not working using angularjs - angularjs

I am trying to create a new custom filter which will remove duplicates from the array of numbers , there's no error but no output as well , can someone please tell me what is wrong.
HTML CODE :
<!DOCTYPE>
<html>
<head>
</head>
<body>
<div ng-app="myApp">
<div ng-controller="myCont">
<div ng-repeat="num in uniqueArray | unique">
checking numbers :
{{num}}
</div>
</div>
</div>
<script src="jquery-3.0.0.js"></script>
<script src="angular.js"></script>
<script src="angular_try.js"></script>
</body>
</html>
Angular js code :
var myApp = angular.module("myApp",[])
myApp.controller("myCont",["$scope","$filter",function($scope,$filter){
$scope.uniqueArray = [5,10,500,2,6,5,4,10,20,5]
}])
myApp.filter("unique",function(){
var arrNumb = [];
var arrNumb2 =[];
return function(input){
angular.forEach(input,function(value,index,obj){
if(arrNumb.indexOf(value)==-1)
{
arrNumb.push(index);
arrNumb2.push(value);
}
})
}
return arrNumb2;
})
But there's nothing on the screen what am I doing wrong ???

You've probably just misplaced a return statement. Put return arrNumb2; inside the inner returned function (move it up one line)
Also, as suggested in the comments, try moving the declarations inside as well.
var myApp = angular.module("myApp",[])
myApp.controller("myCont",["$scope","$filter",function($scope,$filter){
$scope.uniqueArray = [5,10,500,2,6,5,4,10,20,5]
}])
myApp.filter("unique",function(){
return function(input){
var arrNumb = [];
var arrNumb2 =[];
angular.forEach(input,function(value,index,obj){
console.log("protima koo koo ")
//arrNumb.push(value[name])
if(arrNumb.indexOf(value)==-1)
{
arrNumb.push(index);
arrNumb2.push(value);
}
})
return arrNumb2;
}
})

Related

ng-repeat is not working with the key value pair when key has special character($)

ng-repeat is not working with the key value pair when key has special character($)
for an example
<div ng-repeat="(key, value) in values">{{key}}</div>
where values is equal to
$scope.values = {
$firstName:"Kusum";
lastName:"Kumari"
}
its prints the lastNAme but it is failing for $firstName.
Access it like
{{Obj["$firstName"]}}
Notice: the double quotes
You were building the variable in wrong way. Here is a working example.
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.values = [];
$scope.values[0]= {};
$scope.values[0] = {
$firstName:"Kusum",
lastName:"Kumari"
}
});
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app">
<div ng-controller="Controller">
<div ng-repeat="(key, value) in values">{{value.$firstName}}-{{value.lastName}}</div>
</div>
</body>
</html>
This is to be expected, as stated in the docs
ngRepeat will silently ignore object keys starting with $, because
it's a prefix used by Angular for public ($) and private ($$)
properties.
You could change the attributes that begin with a $ in your controller.
for (var property in $scope.values) {
if ($scope.values.hasOwnProperty(property)) {
if(property[0] === '$'){
$scope.values["_"+property] = $scope.values[property]
}
}
}
And you can clean the object afterwards
$scope.clean = function(){
for (var property in $scope.values) {
if ($scope.values.hasOwnProperty(property)) {
if(property[0] === '_'){
console.log($scope.values)
delete $scope.values[property]
}
}
}
}
Here is a working plunker
You can make use Object.keys and a method which returns an Array, which you can iterate through. i.e.
$scope.keys = function(value) {
return value ? Object.keys($scope.values):[];
}
You can use this keys variable in the template
<div ng-repeat="key in keys(values)">
{{key}} : {{values[key]}}
</div>

How do I send a div value to a function in angular controller

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span></li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
<p>{{errortext}}</p>
</div>
</body>
</html>
The line <input ng-model="addMe"> takes the input values and adds to the list
What if I want to define a <div> instead of <input> to send the value to my controller instead of <input> ? I have been trying this for long now and can not get a value enclosed between <div> and </div> sent over to the controller.
Just put your x as parameter on addToCart to add it to cart in the controller.
See demo here.

ng-hide /ng-show do not work after the model is updated

I have the following
var model =
{
UserInfo :null ,
PlatformID : 1
}
var myApp = angular.module("myApp", []);
myApp.controller("UCtrl",['$scope','$http','$window', function ($scope, $http,$window) {
$scope.Info =model ;
$scope.SearchUser = function() {
$http({
method:"POST",
url : '/FindUser',
data: {UserID : 9999}
}).success(function(data){
$scope.Info.UserInfo = data;
});
};
});
<div ng-hide="{{Info.UserInfo === null}}" >
</div>
When a user is searched for , the Info.User is updated via $http post via
$scope.Info.User = data ;
The ng-hide part does not show after the data is assigned to the Info.User object even though there is data.
Don't user {{}} inside ng-if. Expression will be executed anyway:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
</head>
<body ng-app="Example">
<div data-ng-controller="Cntrl">
<div ng-hide="UserInfo === null" >
User info
</div>
<button data-ng-click="toggle()">Toggle</button>
</div>
<script>
var app = angular.module("Example", [])
.controller("Cntrl", function ($scope) {
$scope.UserInfo = null;
$scope.toggle = function () {
if ($scope.UserInfo === null) {
$scope.UserInfo = 'some value';
} else {
$scope.UserInfo = null;
}
};
});
</script>
</body>
</html>
EDIT: here is another fiddle with code more like yours: http://jsfiddle.net/kpLe544u/3/
I think the issue is that you haven't declared a controller in your HTML so you cannot access the variable Info.UserInfo from that div.
Excerpts from my fiddle: (http://jsfiddle.net/kpLe544u/2/)
HTML
<div ng-app>
<div ng-controller="MyCtrl">
<div ng-show="Info.User">data here</div>
<div ng-show="Info.Test">this won't show</div>
</div>
</div>
controller.js
function MyCtrl($scope) {
$scope.Info = {};
$scope.Info.User = "blah blah";
$scope.Info.Test = null;
}

How to $watch multiples properties simultaneous and interpolate into one expression?

Suppose two input fields - name and text. How to simultaneous watch this two fields and interpolate their value into one expression?
Thanks!
Update 9/7/2014:
I did this Plunkr with a working version of the code :)
Thanks Mohammad Sepahvand!
Code:
<!doctype html>
<html ng-app="myApp">
<head>
<title>Interpolate String Template Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.js"></script>
<script type="text/javascript">
angular.module('myApp', ['emailParser']).controller('MyController', ['$scope', 'EmailParser', function ($scope, EmailParser) {
// init
$scope.to = '';
$scope.emailBody = '';
$scope.$watchCollection('[to, emailBody]', function (newValues, oldValues) {
// do stuff here
// newValues and oldValues contain the new and respectively old value
// of the observed collection array
if (newValues[0] && newValues[1]) { // there's name and some text?
$scope.previewText = EmailParser.parse(newValues[1], {to: $scope.to});
}
});
}]);
angular.module('emailParser', []).config(['$interpolateProvider', function ($interpolateProvider) {
$interpolateProvider.startSymbol('__');
$interpolateProvider.endSymbol('__');
}]).factory('EmailParser', ['$interpolate', function ($interpolate) { // create service
return {
parse: function (text, propertiesToBeInterpolated) { // handle parsing
var template = $interpolate(text);
return template(propertiesToBeInterpolated);
}
};
}]);
</script>
</head>
<body>
<h3>Instructions in readme.md file - please read before!</h3>
<div id="emailEditor" ng-controller="MyController">
<label>*Name:</label>
<input ng-model="to" type="text" placeholder="Ex.: John"/>
<br><br>
<label>*Text:</label><br>
<textarea ng-model="emailBody" cols="25" rows="10" placeholder="Write something"></textarea>
<p style="color:red;">*required</p>
<div>
<pre>__previewText__</pre>
</div>
</div>
</body>
</html>
You can use the $watchGroup method that was added in angular 1.3:
$scope.$watchGroup(['prop1', 'prop2'], function(newValues, oldValues, scope) {
var prop1 =newValues[0];
var prop2 =newValues[1];
});
Or you could use $watchCollection which has been available since angular 1.1.4:
scope.$watchCollection('[prop1, prop2]', function(newValues, oldValues){
});

broadcasting model changes

I'm trying to set up a little POC to see whether or not angular would work for something I'm in the middle of.
I set up a REST server which I am able to CRUD with via angular. However, as the documentation and tutorials out there are so all over the place (read: SUPER inconsistent), I am not sure that the behavior I'm not seeing is the result of incorrect code or it's not something I can do like this.
I've gleaned from the docs that two-way binding is available, but it isn't clear how it works. NB I've read dozens of articles explaining how it works at a low level a'la https://stackoverflow.com/a/9693933/2044377 but haven't been able to answer my own question.
I have angular speaking to a REST service which modifies a sql db.
What I am wondering about and am trying to POC is if I have 2 browsers open and I change a value in the db, will it reflect in the other browser window?
As I said, I have it updating the db, but as of now it is not updating the other browser window.
app.js
angular.module('myApp', ['ngResource']);
var appMock = angular.module('appMock', ['myApp', 'ngMockE2E']);
appMock.run(function($httpBackend) {});
controllers.js
function MainCtrl($scope, $http, $resource) {
$scope.message = "";
$scope.fruits = [];
$scope.fruit = {};
$scope.view = 'partials/list.html';
var _URL_ = '/cirest/index.php/rest/fruit';
function _use_$resources_() { return false; }
function _fn_error(err) {
$scope.message = err;
}
$scope.listFruits = function() {
$scope.view = 'partials/list.html';
var fn_success = function(data) {
$scope.fruits = data;
};
$http.get(_URL_).success(fn_success).error(_fn_error);
}
function _fn_success_put_post(data) {
$scope.fruit = {};
$scope.listFruits();
}
function createFruit() {
$http.post(_URL_, $scope.fruit).success(function(data){
$scope.listFruits()
}).error(_fn_error);
}
function updateFruit() {
$http.post(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
function deleteFruit() {
$http.put(_URL_, $scope.fruit).success(_fn_success_put_post).error(_fn_error);
}
$scope.delete = function(id) {
if (!confirm("Are you sure you want do delete the fruit?")) return;
$http.delete("/cirest/index.php/rest/fruit?id=" + id).success(_fn_success_put_post).error(_fn_error);
}
$scope.newFruit = function() {
$scope.fruit = {};
$scope.fruitOperation = "New fruit";
$scope.buttonLabel = "Create";
$scope.view = "partials/form.html";
}
$scope.edit = function(id) {
$scope.fruitOperation = "Modify fruit";
$scope.buttonLabel = "Save";
$scope.message = "";
var fn_success = function(data) {
$scope.fruit = {};
$scope.fruit.id = id;
$scope.view = 'partials/form.html';
};
$http.get(_URL_ + '/' + id).success(fn_success).error(_fn_error);
}
$scope.save = function() {
if ($scope.fruit.id) {
updateFruit();
}
else {
createFruit();
}
}
$scope.cancel = function() {
$scope.message = "";
$scope.fruit = {};
$scope.fruits = [];
$scope.listFruits();
}
$scope.listFruits();
}
MainCtrl.$inject = ['$scope', '$http', '$resource'];
list.html
{{message}}
<hr/>
New Fruit
<ul ng-model="listFruit">
<li ng-repeat="fruit in fruits">
id [{{fruit.id}}] {{fruit.name}} is {{fruit.color}}
[X]
</li>
</ul>
index.html
<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>FRUUUUUUUUUUUUUUUUUUUUUUUUUUUIT</title>
<link rel="stylesheet" href="css/bootstrap/css/bootstrap.css"/>
</head>
<body>
<div class="navbar">NAVBARRRRRRRRRRR</div>
<div class="container">
<div class="row">
<div ng-controller="MainCtrl">
<button ng-click="listFruits()">ListFruit()</button>
<button ng-click="cancel()">Cancel()</button>
<ng-include src="view"></ng-include>
</div>
</div>
</div>
<!-- In production use:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>
-->
<script src="lib/angular/angular.js"></script>
<script src="lib/angular/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
</body>
</html>
form.html
<h3>{{fruitOperation}}</h3>
<hr/>
<form name="fruitForm">
<input type="hidden" name="" ng-model="fruit.id" />
<p><label>name</label><input type="text" name="name" ng-model="fruit.name" value="dfgdfgdfg" required="true" /></p>
<p><label>color</label><input type="text" name="color" ng-model="fruit.color" value="fruit.color" required="true" /></p>
<hr/>
<input type="submit" ng-click="save()" value="{{buttonLabel}}" /> <button ng-click="cancel()">Cancel</button>
</form>
Thanks for any insight or pointers.
Two-way binding refers to changes occurring in your controller's scope showing up in your views and vice-versa. Angular does not have any implicit knowledge of your server-side data. In order for your changes to show up in another open browser window, for example, you will need to have a notification layer which pushes changes to the client via long polling, web sockets, etc.

Resources