I am having issues getting the ng-repeat to walkthrough my JSON response, I am new to AngularJS so I am sure its a newbie mistake :). I am trying to have the ng-repeat go through the ns0:AttributeDetails, ns0:Attributes. Here is the JSON data:
{"ns0:GetAgentProfile.Response": {
"xmlns:ns0": "http://URL",
"ns1:Header": {
"xmlns:ns1": "http://URL",
"xmlns:ns7": "http://URL",
"ns1:Source": null,
"ns1:CreatedDateTime": "2014-03-24T09:34:28.339-05:00",
"ns1:MessageType": "Request",
"ns1:MessageId": null
},
"ns0:ProfileDetails": {
"ns0:UserIdentifier": {
"ns0:UserGUID": "2BCF0074-392F-4653-8733-02063C2DBC5C",
"ns0:UserName": "Username01"
},
"ns0:AttributeDetails": {"ns0:Attribute": [
{
"ns0:Name": "AgentLogin",
"ns0:Value": ["Username01"]
},
{
"ns0:Name": "FullName",
"ns0:Value": ["Name, User"]
},
{
"ns0:Name": "LanguageSpoken",
"ns0:Value": ["English|Chinese"]
},
{"ns0:Name": "Supervisor"},
{
"ns0:Name": "Region",
"ns0:Value": ["Region01"]
},
{
"ns0:Name": "Country",
"ns0:Value": ["CO"]
},
{
"ns0:Name": "ClientAccessGroup",
"ns0:Value": ["CountryMobileCCR"]
},
{"ns0:Name": "Roles"}
]},
Here is the HTML:
<!DOCTYPE html>
<html ng-app="auth" xmlns="http://www.w3.org/1999/html">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="js/bootstrap.js"></script>
<script src="js/angular.js"></script>
<script src="js/authorization.js"></script>
</head>
<body ng-controller="MainCtrl">
<div>
<div class="container-fluid">
<form class="well">
<label>Username:</label>
<input><br><br>
<button ng-click="getData()" class="btn btn-primary">Submit</button>
<button ng-click="clearData()" class="btn btn-danger">Reset</button>
</form>
</div>
<h1>Response from Service:</h1>
<!-- <pre>{{data | json}}</pre> -->
<pre>
Username: {{data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails'] ['ns0:UserIdentifier']['ns0:UserName']}} <br>
Profile Details</pre>
<div ng-repeat="Attribute in data">{{ data['ns0:GetAgentProfile.Response']['ns0:ProfileDetails']['ns0:AttributeDetails']['ns0:Attribute']['ns0:Name'] }}</div>
</div>
</html>
Here is the JS for the controller fetching the data:
var app = angular.module('auth', []);
app.factory('authService', function($http) {
var promise;
var authService = {
async: function() {
if ( !promise ) {
promise = $http.get('package.json').then(function (response) {
console.log(response);
return response.data;
});
}
return promise;
}
};
return authService;
});
app.controller('MainCtrl', function( authService,$scope) {
$scope.clearData = function() {
$scope.data = {};
};
$scope.getData = function() {
authService.async().then(function(d) {
$scope.data = d;
});
};
});
Again I apologize for the newbie question. Any assistance would be greatly appreciated.
Drill down to your array in the repeat directive:
<div ng-repeat="Attribute in data.ns0:GetAgentProfile.Response.ns0:ProfileDetails.ns0:AttributeDetails.ns0:Attribute">
And now you can do:
{{Attribute.ns0:Name}} and {{Attribute.ns0:Value}}
Not sure if the : will play nicely tho, may have to escape those.
Related
Angular js filter Working Fine But Throwing Itteration Errors
var app = angular.module('NGapp', []);
app.filter('altDate', altDate);
app.controller('MainCtrl', MainCtrl)
function MainCtrl($scope) {
$scope.data = {
'listProductCost': [{
'data': 1
}, {
'data': 23
}, {
'data': 234
}, ]
}
}
function altDate(_) {
return function(value) {
console.log(value)
if (!value || value.length === 0) {
return [];
} else {
var f = []
angular.forEach(value, function(data) {
f.push(data['data']);
})
var s = []
s.push({
'min': _.min(f),
'max': _.max(f)
})
return s;
}
//return s;
};
}
app.factory('_', LodashFactory);
/** #ngInject */
function LodashFactory($window) {
return $window._;
}
<!DOCTYPE html>
<html ng-app="NGapp">
<head>
<meta charset="utf-8" />
<title>AngularJS </title>
<link rel="stylesheet" href="style.css" />
<script data-require="lodash.js#4.17.4" data-semver="4.17.4" src="https://cdn.jsdelivr.net/npm/lodash#4.17.4/lodash.min.js"></script>
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<md-card-content layout="row" layout-align="none" ng-repeat="datas in data.listProductCost | altDate ">
<div class="dark" flex="30">HO Cost</div>
<div>
<span>{{datas.min}}</span> % to <span>{{datas.max}}</span> %
</div>
</md-card-content>
</body>
</html>
Here is my Working Code With angularjs filter . the filter is working fine but iam getting itteration error in console
the purpose filter is to print only the minimum and maximum value of the discount. can anyone can resolve the issue or give me a idea to resolve this thanks in advance
I see you using lodash. Why not use _.minBy() instead of _.min() ?
That way you can reduce your altDate function to
altDate(_){
return function(value) {
return {
min: _.minBy(value, function(i) { return i.data }),
max: _.maxBy(value, function(i) { return i.data})
}
}
}
i've tried to add an object to my array savedTemplates in a service with the function getTemplates.
I've used a service for this in order to access the templates in multiple views.
Unfortunately, if i try to call my function, nothing happens.
services.js:
.factory('templateData', function(){
var savedTemplates = [
{"name":"Adam Müller", "iban":"AT29100020003000","image":"adam.jpg"},
{"name":"Ben Streicher","iban":"AT34900080007000","image":"ben.png"},
{"name":"Max Krossmann","iban":"AT23400050006000","image":"max.png"}
];
var getTemplates = function(){
return savedTemplates;
};
var addTemplates = function(insertName,insertIban){
savedTemplates.push=({"name": insertName, "iban": insertIban, "image": 'mike.png'});
alert("This is savedTemplates:" + savedTemplates);
};
return {
getTemplates:getTemplates,
addTemplates:addTemplates
};
})
template-save.html:
<button class="button button-large button-positive" ng-click="addTemplates(newreceiver,newiban)" ui-sref="tab.templates">
Speichern
</button>
I would be very grateful for any help, since I'm quite desperated already.
Here is a sample snippet.
You also have a problem in your factory addTemplates code, you should use savedTemplates.push ({ ... }], not savedTemplates.push = ({ ... }]
Snippet
angular.module('app', []);
angular.
module('app')
.controller('ExampleController', ['$scope', 'templateData', function($scope, templateData) {
$scope.addTemplates = templateData.addTemplates;
}])
.factory('templateData', function() {
var savedTemplates = [{
"name": "Adam Müller",
"iban": "AT29100020003000",
"image": "adam.jpg"
},
{
"name": "Ben Streicher",
"iban": "AT34900080007000",
"image": "ben.png"
},
{
"name": "Max Krossmann",
"iban": "AT23400050006000",
"image": "max.png"
}
];
var getTemplates = function() {
return savedTemplates;
};
var addTemplates = function(insertName, insertIban) {
savedTemplates.push ({
"name": insertName,
"iban": insertIban,
"image": 'mike.png'
});
console.log("This is savedTemplates:" + JSON.stringify(savedTemplates, null, 2));
};
return {
getTemplates: getTemplates,
addTemplates: addTemplates
};
});
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ExampleController">
<button ng-click="addTemplates('Marty McFly', 'BTTF900080007000')">
Speichern
</button>
</body>
</html>
I have a Kendo model instance (person for this example) and watching it is modified or not by using dirty property.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kendo + Angular</title>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.default.min.css">
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.714/styles/kendo.mobile.all.min.css">
<script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/angular.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/jszip.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2016.2.714/js/kendo.all.min.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="MainCtrl">
<div>Person name: {{ person.name }}</div>
<input type="text" name="name" ng-model="person.name"> <!-- This input don't work -->
<button ng-click="foo()">Foo</button> <!-- This button work because I call person.set method manually -->
<div>This person is modified? {{ person.dirty }}</div>
</div>
<script>
var Person = kendo.data.Model.define({
id: "personId", // the identifier of the model
fields: {
"name": {
type: "string"
},
"age": {
type: "number"
}
}
});
angular.module("app", ["kendo.directives"])
.controller("MainCtrl", function ($scope) {
$scope.person = new Person({
name: "John Doe",
age: 42
});
$scope.foo = function () {
$scope.person.set('name', "Kendo");
}
});
</script>
</body>
</html>
But when I type to text box dirty don't change because Angular ngModel doesn't fire Kendo "change" event. My real app have dozens of models like this, so is there any way to fix this automatically???
Thanks.
You can write a directive to replace for ng-model,
<input type="text" name="name" k-bind-model="person.name">
angular.module('app')
.directive("kBindModel", ["$parse", function ($parse) {
return {
restrict: "A",
scope: false,
link: function (scope, element, attributes, controller) {
var key = null;
var strs = attributes.kBindModel.split('.');
if (strs && strs.length > 1) {
key = strs[1];
}
var model = scope[strs[0]];
element.change(function () {
scope.$apply(function () {
model.set(key, element.val());
});
});
scope.$watch(attributes.kBindModel, function (n, o) {
element.val(n);
});
}
}
}]);
I'm taking a pool of random animals, displaying two, then when I click the button of one animal, I want that one to stay and the other to be swapped out for a new one. Right now, I can change the animal that I want to stay in view, but can't figure out how to "reach across" and change the other controller's view.
I've tried setting ng-click="left.findNewAnimal()" on the right side but I get no response on click.
I've also looked at using a service or factory, but I'm not sharing data between controllers, I want to change the data of one, from the other. How can this be accomplished?
JavaScript:
angular.module("root", [])
.controller("leftAnimal", ["$scope",
function($scope) {
var self = this;
var animal
$scope.findNewAnimal = function() {
var randNum = Math.floor(Math.random() * animalPool.length);
animal = animalPool[randNum];
animalPool.splice(randNum, 1)
changeAnimal();
};
$scope.findNewAnimal();
function changeAnimal() {
$scope.name = animal.name;
$scope.img = animal.img;
}
}
])
.controller("rightAnimal", ["$scope",
function($scope) {
var self = this;
var animal
$scope.findNewAnimal = function() {
var randNum = Math.floor(Math.random() * animalPool.length);
animal = animalPool[randNum];
animalPool.splice(randNum, 1)
changeAnimal();
};
$scope.findNewAnimal();
function changeAnimal() {
$scope.name = animal.name;
$scope.img = animal.img;
}
}
])
.factory();
var Animal = function(data) {
this.name = data.name
this.img = data.img;
this.baby = data.baby;
};
var animals = [{
name: "Baby Quetzal",
img: "http://i.imgur.com/CtnEDpM.jpg",
baby: true
}, {
name: "Baby Otter",
img: "http://i.imgur.com/1IShHRT.jpg",
baby: true
}, {
name: "Baby Octopus",
img: "http://i.imgur.com/kzarlKW.jpg",
baby: true
}];
var animalPool = [];
var init = function() {
animals.forEach(function(animalData) {
animalPool.push(new Animal(animalData));
});
}
init();
<!doctype html>
<html ng-app="root">
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/main.css">
</head>
<body>
<div class="row">
<div class="text-center">
<h2>Pick an Animal</h2>
</div>
<div ng-controller="leftAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{img}}">
</div>
<div class="animalName">{{name}}</div>
<div class="animalDescription">{{description}}</div>
<button type="button" ng-click="findNewAnimal()" class="btn btn-info img-center">{{name}}</button>
</div>
<div ng-controller="rightAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{img}}">
</div>
<div class="animalName">{{name}}</div>
<div class="animalDescription">{{description}}</div>
<button type="button" ng-click="leftAnimal.findNewAnimal()" class="btn btn-info img-center">{{name}}</button>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="js/ang.js"></script>
</html>
If you only want simple event exchange between controllers you can use
$scope.$emit and $scope.$on :
//right
<button type="button" ng-click="emitEvent()" class="btn btn-info img-center">{{name}}</button>
//right controller
$scope.emitEvent = function(){
$scope.$emit('changeAnimal');
}
//left controller
$scope.$on('changeAnimal', function(event){
//do stuff
})
More on $scope events in official docs
As you stated, you can use Service to communicate to between controllers.
If you want to update other controller update automatically, you want to watch it.
http://plnkr.co/edit/iLnlZDyR1cZUQIiJJJEp
(function () {
angular.module("root", [])
.controller("leftAnimal", ["$scope", "animalService",
function ($scope, animalService) {
var source = false;
$scope.findNewAnimal = function () {
var randNum = Math.floor(Math.random() * animalPool.length);
console.log("Left Click Index: " + randNum);
animalService.setAnimal(randNum);
source = true;
};
$scope.$watch(function () {
return animalService.getAnimal();
}, function (value) {
if(!source) {
$scope.animal = animalPool[value];
}
source = false;
});
}
])
.controller("rightAnimal", ["$scope", "animalService",
function ($scope, animalService) {
var source = false;
$scope.findNewAnimal = function () {
var randNum = Math.floor(Math.random() * animalPool.length);
console.log("Right Click Index: " + randNum);
animalService.setAnimal(randNum);
source = true;
};
$scope.$watch(function () {
return animalService.getAnimal();
}, function (value) {
if(!source) {
$scope.animal = animalPool[value];
}
source = false;
});
}
])
.factory("animalService", [function () {
var index = 0;
function getAnimal() {
return index;
}
function setAnimal(newIndex) {
index = newIndex;
}
return {
getAnimal: getAnimal,
setAnimal: setAnimal,
}
}]);
var animalPool = [{
name: "Baby Quetzal",
img: "http://i.imgur.com/CtnEDpM.jpg",
baby: true
}, {
name: "Baby Otter",
img: "http://i.imgur.com/1IShHRT.jpg",
baby: true
}, {
name: "Baby Octopus",
img: "http://i.imgur.com/kzarlKW.jpg",
baby: true
}];
})();
<!DOCTYPE html>
<html ng-app="root">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="row">
<div class="text-center">
<h2>Pick an Animal</h2>
</div>
<div ng-controller="leftAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{animal.img}}"/>
</div>
<div class="animalName">{{animal.name}}</div>
<div class="animalDescription">{{animal.description}}</div>
<button type="button" ng-click="findNewAnimal()"
class="btn btn-info img-center">
Change
</button>
</div>
<div ng-controller="rightAnimal" class="col-md-6">
<div class="animalImage">
<img class="img-center" ng-src="{{animal.img}}" />
</div>
<div class="animalName">{{animal.name}}</div>
<div class="animalDescription">{{animal.description}}</div>
<button type="button" ng-click="findNewAnimal()"
class="btn btn-info img-center">
Change
</button>
</div>
</div>
</body>
</html>
I'm coding a web app in html, AngularJS and REST (rest modified for my teachers).
My program should load participants in a select in the openning. But show i.e {{participants.name}} and not {{Jhon}}
The problem is at the moment that would load method "search".
Error:
"Error: Birthday.search is not a function
$scope.updateList#localhost:9000/birthday.js:26:1
#localhost:9000/birthday.js:31:5
e#localhost:9000/node_modules/angular/angular.min.js:36:313
Fe/this.$get
HTML:
<!DOCTYPE html>
<html lang="es" data-ng-app="birthdayApp">
<html>
<head>
<meta charset="utf-8">
<script src="node_modules/jquery/dist/jquery.min.js"></script>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="node_modules/angular/angular.min.js"></script>
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/estilo.css">
<script src="birthday.js"></script>
</head>
[...]
<body>
<div class="container-fluid" data-ng-controller="BirthdayControllers as birthday">
[...]
<select size="2" class="col-lg-12 col-md-12 col-xs-12">
<option data-ng-repeat="participant in participants | filter:filter"> {{participant.name}} </option>
</select>
[...]
The head its ok?
AngularJS
'use strict';
var app = angular.module("birthdayApp", [])
app.factory('Birthday', function($http) {
return function(errorHandler) {
this.search = function(callback, errorHandler) {
$http.get('/participants').success(callback).catch(errorHandler);
}
}
});
/* Controllers */
app.controller("BirthdayControllers", function($scope, Birthday) {
$scope.participants = null;
var errorHandler = function(error) {
$scope.notificarError(error.data);
};
$scope.updateList = function() {
Birthday.search(function(data) { //here stop, here the problem!
$scope.participants = data;
}, errorHandler);
}
$scope.updateList();
[...]
});
My factories look different. Here's how I do mine:
app.factory('Birthday', function ($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
Controller would look like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).error(function(data, status, headers, config) {
//handle the error
});
You need to return a factory object from the function not another function.
So modify your code like this:
app.factory('Birthday', function($http) {
return {
search: function() {
return $http.get('/participants');
}
};
});
It's better to handle the callbacks in the controller, so call the factory method like this:
Birthday.search().success(function(data) {
$scope.participants = data;
}).catch(function(error) {
$scope.notificarError(error.data);
});