HTML5 Import and Angular controller binding - angularjs

Given
I'm using HTML5 web components via the <link rel="import..." construct. Am
able to breakup large HTML markup into smaller portions and import them at will into a container (web page) that puts all the smaller parts together. Cool so far.
Now I want to use Angular data binding to be able to show dynamic content in those smaller pages. In my main Index.html page I am able to declare the ng-app in the first Div tag no problem. The angular.module is declared in that page as well. I can get the binding to work if I put all controller logic into main page.
Problem
I'd like to do is split each controller script shown below to be contained in the imported page and not just in the main index.html where it's working now.
<script>
angular.module('ResultsApp', [])
.controller('CardsController', ['$scope',
function ($scope) {
$scope.results = {
'Passed': '12',
'Failed': '3',
'Warnings': '5',
'Summary': '20'
}
}
])
.controller('ResultsController', ['$scope',
function ($scope) {
$scope.results = [
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" },
{ Name: "The Name of something to display", Passed: "True", Failed: "False", Comments: "These are the comments yes! Comments" }
];
}]);
</script>
I've tried putting the controller logic into each imported page but it doesn't seem to work. I am only attempting to use one ng-app defined in main page... Please advise.
Ok if I move the code to a partial page like this, where TestResultsApp is on the main page (Index) call this page "pageheading.html" :
<div class="row" ng-controller="HeaderController">
<div class="col-lg-12">
<h1 class="page-header">
{{header.Title}}
</h1>
<ol class="breadcrumb">
<li class="active">
<i class="fa fa-dashboard">Some Data Here</i>
</li>
</ol>
</div>
</div>
<script>
angular.module('HeaderModule', ['TestResultsApp'])
.controller('HeaderController', ['$scope',
function ($scope) {
$scope.header = { "Title": "Pretty Good, Test Case Results Right here!" }
}])
</script>
The New Error
The partial page, can't find angular... More on this tomorrow...

If I am reading this right, you'll need to use ng-controller on each page that utilizes the controller, and it should work.

Related

How to check if the ng-repeat in view is empty after certain conditions match

I have an object coming from the JSON.
I use ng-repeat to display the object.
In order to show certain rows-only, I use if condition and not filter.
My question is, after I use if condition and if there is none of the rows matching the condition, I need to show an "empty" alert. How can I do that?
As of now my object is like this
[{
"task_id":3773,
"task_name":"King of Avalon: Dragon War",
"task_status":"pending"
},
{
"task_id":2208,
"task_name":"Final Fantasy XV",
"task_status":"pending"
},
{
"task_id":3760,
"task_name":"King of Avalon: Dragon War",
"task_status":"pending"
},
{
"task_id":2746,
"task_name":"Postmates",
"task_status":"complete"
}]
As you can see the column 'task_status'. There are various values to it : 'complete', 'pending', 'new'.
I'm using the following code to display to the 'new' tasks alone.
<div ng-repeat="(key, task) in tasksObj" ng-if="task.task_status == 'new'>
<p>{{task.task_id}}</p>
</div>
How do I display an empty rows error when there is no 'new' tasks available?
You can write that logic in controller where you can check if all the task do not have new status and alert accordingly.
angular.module('app', [])
.controller('MainCtrl', ['$scope', function($scope) {
$scope.tasksObj = [{
"task_id": 3773,
"task_name": "King of Avalon: Dragon War",
"task_status": "pending"
}, {
"task_id": 2208,
"task_name": "Final Fantasy XV",
"task_status": "pending"
}, {
"task_id": 3760,
"task_name": "King of Avalon: Dragon War",
"task_status": "pending"
}, {
"task_id": 2746,
"task_name": "Postmates",
"task_status": "complete"
}];
let nonNewStatus = $scope.tasksObj.every(({task_status}) => task_status!=='new');
if(nonNewStatus) {
alert('There is no any task with status: new');
}
}])
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
<div ng-repeat="(key, task) in tasksObj" ng-if="task.task_status =='new'">
<p>{{task.task_id}}</p>
</div>
</div>

JSON file not importing?

I'm still pretty new to AngularJS, but this concerns importing from a JSON document.
I have a list of guitars which I've made all as objects in my JS file (And had it all working correctly), and I use ng-repeat to have all of them display. Now, I want to place those objects in a separate JSON file.
HTML template:
<section id="guitarSections" ng-controller="GuitarCtrl">
<div id="guitarDivs" data-ng-repeat="guitar in guitars">
<img id="guitarImages" src="{{guitar.imageURL}}">
<div id="text">
<h2 class="information">{{guitar.title}}</h2>
<p class="information">Instrument: {{guitar.instrument}}<p>
<p class="information">Color: {{guitar.color}}</p>
<p class="information">Price: {{guitar.price}}</p>
</div>
</div>
<br>
</section>
JS
var app = angular.module("myApp", []);
app.controller("GuitarCtrl", function($scope, $http) {
var url = "data.json";
$http.get(url).then(function(response) {
$scope.guitars = response.data;
});
});
And a small sample of my JSON:
{
"guitars":[
{
"title": "Yamaha Revstar 420",
"brand": "Yamaha",
"instrument": "Electric Guitar",
"color": "Red",
"price": "$499.99",
"details": "Yes",
"imageURL": "YamahaRS420.jpg"
},
{
"title": "Yamaha Pacifica Series PAC012",
"brand": "Yamaha",
"instrument": "Electric Guitar",
"color": "Blue",
"price": "$",
"details": "Yes",
"imageURL": "YamahaPacificaSeriesPAC012.jpg"
}
]}
When I run it on a Python Server (python -m SimpleHTTPServer), the page loads, but none of the content will get imported over and it only shows one guitar section.
ADDITIONAL NOTE: I also inspected the Network, and in the columns with the names of the documents, I happened to notice, in red, '%7B%7Bguitar.imageURL%7D%7D'. Upon examining this, a page pops up and gives me a 404, which says:
Error code 404.
Message: File not found.
Error code explanation: 404 = Nothing matches the given URI.
Though I have checked and ensured that all of my documents' names are not misspelled and that each image can be imported.
First, you expect your JSON to contain an array of guitars, but it actually contains an object with a single attribute named guitars.
Second, you should use ng-src rather than src for your IMG element, to avoid this request to a non-interpolated URL.

JSON Data not displaying on Ionic HTML Template

I have been trying to find the reason why my Ionic template is not displaying JSON data. I just started working and reading on ionic framework and angularjs.
please bear with my newbie questions;
1.) what is the error or cause why the json record is not displaying on the HTML?
2.) I have seen plenty of code samples where the Json codes is written on the controller.js instead on the services.js. Which one is standard and safe?
3.) I am having doubts regarding my json output, Can someone please confirm if the format is correct.
You help on this is really appreciated,. thanks in advance
here is my Console status:
Objectconfig: Objectdata: Array[1]0: Array[1]0: Array[1]0:
Objectcapacity: "7"fuelcap: "120"
make: "Nissan"model: "LoadMaster II"platenumber: "TRG0122"
vehiclecode: "TRK0004"vehicleid: "8"wheelnumber: "10"
__proto__: Objectlength: 1__proto__: Array[0]
length: 1__proto__: Array[0]length: 1__proto__: Array[0]headers: (name)status: 200statusText: "OK"__proto__: Object
On my template/HTML file:
<ion-list id="vehicleInformation-list1" class=" " ng-repeat="recs in vehiclerecord">
<ion-item id="vehicleInformation-list-item1" class=" ">Vehicle Model
<span class="item-note">{{ recs.model }}</span>
</ion-item>
</ion-list>
My Controller file:
.controller('vehicleInformationCtrl', function($scope, $http) { // TIP: Access Route Parameters for your page via $stateParams.parameterName
// var _this = this;
$http.get('http://myurlsample.com/webserve/').then(function(vehicleinfo ) {
$scope.vehiclerecord = vehicleinfo.data;
console.log(vehicleinfo);
alert(JSON.stringify(vehicleinfo));
}).catch(function(vehicleinfo)
{
console.log(vehicleinfo);
});
})
my Route.js file contains:
.state('tabsController.vehicleInformation', {
url: '/vehicleinfo',
views: {
'tab4': {
templateUrl: 'templates/vehicleInformation.html',
controller: 'vehicleInformationCtrl'
}
}
})
Via Jsonview a record look like this;
[
[
[
{
vehicleid: "8",
platenumber: "TRG0122",
make: "Nissan",
model: "LoadMaster II",
capacity: "7",
fuelcap: "120",
wheelnumber: "10",
vehiclecode: "TRK0004"
}
]
]
]
If I'm reading your jsonview output correctly, it looks like there's a lot of nesting going on:
[[[{model: "LoadMaster II", ...}]]]
The ng-repeat you have there will only work if the $scope.vehiclerecord looks like this:
[{model: "LoadMaster II", ...}, ... ]
Note that this is simply an array of objects with no nested arrays like your jsonview output.
So the solution is to play with vehicleinfo.data from the http response until you have only an array of objects. Based on the jsonview you have there, this would work:
$scope.vehiclerecord = vehicleinfo.data[0][0];

$sce:itype Attempted to trust a non-string value in a content requiring a string: Context: resourceUrl

I want to play songs stored in my sails server. Path is http://localhost:4000/images/123.mp3.
In front end, i'm using ng-repeat to list that songs from server.
<div ng-repeat="tones in ringTones track by $index">
<div>
<i ng-show="playpause" class="fa fa-play-circle" ng-click="playpause=!playpause" onclick="plays(event);"><audio id="audio_{{$index}}" ng-src="tones.tonePath"></audio></i>
<i ng-show="!playpause" class="fa fa-pause" ng-click="playpause=!playpause" onclick="stop(event);"></i></div>
</div>
This audio source cause external resource problem
<audio ng-src="tones.tonePath"></audio>
in angular controller, i'm using $sce
$http.get("http://localhost:4000/songs/find").success(function(data){
$rootScope.ringTones=data;
$rootScope.ringTones.push($sce.trustAsResourceUrl(data[0]));
}).error(function(data){
console.log('ERROR');
});
Error is :
Error: [$sce:itype] Attempted to trust a non-string value in a
content requiring a string: Context: resourceUrl
Without using $sce that cause
Error: [$interpolate:interr] Can't interpolate: tones.tonePath
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy. URL
This is my JSON from server
[{
"toneName": "2",
"aboutTone": "2",
"duration": 2,
"tonePath": "http://localhost:4000/images/234.mp3",
"createdAt": "2015-08-03T15:40:58.227Z",
"updatedAt": "2015-08-03T15:40:58.227Z",
"id": "55bf8b8a77efb94b32b158c0"
},
{
"toneName": "3",
"aboutTone": "3",
"duration": 3,
"tonePath": "http://localhost:4000/images/123.mp3",
"createdAt": "2015-08-03T15:45:16.120Z",
"updatedAt": "2015-08-03T15:45:16.120Z",
"id": "55bf8c8c77efb94b32b158c1"
}
]
Then how to play external mp3 in my ng-repeat. Help me.
I found solution :
External resource not being loaded by AngularJs
app.filter('trusted', ['$sce', function ($sce) {
return function(url) {
return $sce.trustAsResourceUrl(url);
};
}]);
Then specify the filter in ng-src:
<audio
ng-src="{{tones.tonePath | trusted}}" />
</audio>
Thanks for response.
//first Take data from api
$scope.Data= JSLINQ(data.Data).Select(function (Item) { return Item; })
//Map data as trustable to scope
$scope.Data.items.map(function (i) {
i.Header1 = $sce.trustAsHtml(i.Header1);
});
//UI bind modal data
<p ng-bind-html="x1.Header1 " ng-show="x1.Header1 != null"></p>

JSON Angular Array pulling data from 3rd Loop

I am struggling to pull the data from the 3rd loop (Names) in the array below.
Any idea what i am doing wrong?
sample.json
{
"otc": [
{
"name": "Tums",
"language": [
{
"title": "English",
"names": [
{"name": "Tums"},
{"name": "Pepto"}
]
},
{
"title": "China"
},
{
"title": "Germany"
}
,
{
"title": "Mexico"
}
,
{
"title": "India"
}
,
{
"title": "United Kingdom"
}
]
},
{
"name": "Dramamine",
"language": [
{
"title": "title2album1"
},
{
"title": "title2album2"
},
{
"title": "title2album3"
}
]
}
]
}
And this is my index.html
<body ng-app="list">
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat-start="meds in otc">
<strong> {{meds.name}}</strong> //This displays just fine
</li>
<li ng-repeat="lang in meds.language"><em>{{lang.title}}</em></li> //This displays just fine
<li ng-repeat-end ng-repeat="drugs in lang.names">{{drugs.name}}</li> //This doesnt display
</ul>
</div>
<script>
angular.module('list', []);
function ListCtrl($scope, $http) {
$http({method: 'GET', url: 'sample.json'}).success(function(data) {
$scope.otc = [];
angular.forEach(data.otc, function(value, key) {
$scope.otc.push(value);
});
$scope.isVisible = function(name){
return true;
};
});
}
</script>
It looks like your JSON data is a bit incomplete, since you're missing the names key in all of the language objects except for the English one.
Beyond that, your html/angular-view code is a bit off. The ng-repeat's should be nested inside of one-another. This is done by having the opening/closing html tags that contain the ng-repeat directive completely surround the inner <li> tags.
It's a bit hard to tell, but if you want nested lists, you need to add <ul> tags like in my example below.
I believe your index html should look something like:
<ul>
<li ng-repeat="meds in otc">
<strong> {{meds.name}}</strong> //This displays just fine
<ul>
<li ng-repeat="lang in meds.language">
<em>{{lang.title}}</em>
<ul>
<li ng-repeat="drugs in lang.names">{{drugs.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
The reason why the li ng-repeat tags should be nested is because ng-repeat creates its own isolate scope. Which means that inside of an ng-repeat tag, it only has access to the data made available by the ng-repeat="data in datar" part.
So having:
<li ng-repeat="lang in meds.language"><em>{{lang.title}}</em></li> //This displays just fine
<li ng-repeat="drugs in lang.names">{{drugs.name}}</li> //This doesnt display
as sibling elements, and not the second as a child of the other, the 2nd ng-repeat list does not know what the var lang is. So the drugs in lang.names fails.
Btw, this snippet assumes that the output you want is:
Tums
English
Tums
Pepto
China
Germany
etc
Dramamine
title2album1
title2album2
etc
If you wanted the output as a flat list, you can use the following CSS
ul ul {
padding: 0;
margin: 0;
list-style-type: disc;
}

Resources