Dynamic links with angularjs and ng-repeat - javascript

I'm creating an app using fake JSONplaceholder API. I'm displaying a list of posts and I want the ng-repeated post titles to link to the post view.
Here's the HTML:
<body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
<h1>{{apptitle}}</h1>
<script type="text/ng-template" id="allposts.htm">
<a href="#addpost">
<button type="button" class="btn btn-primary addbtn" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Add a post
</button>
</a>
View
<select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
<option>9</option>
<option>18</option>
<option>36</option>
<option>100</option>
</select>posts
<div class="row" ng-repeat="collatedPostList in collatedPosts">
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
<div class="inner">
{{post.title}}
<p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
</div>
</div>
</div>
<div class="text-center">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
</div>
</script>
<script type="text/ng-template" id="posts.htm">
</script>
<script type="text/ng-template" id="addpost.htm">
<form ng-submit="addPost()" class="adding">
<input id="titleadd" type="text" name="title" ng-model="newPost.title" placeholder="Add title">
<br>
<input id="textadd" type="text" name="body" ng-model="newPost.body" placeholder="Add some text">
<br>
<button type="submit" ng-click="addAlert(msg,'success')" class="btn btn-primary" id="submit" value="Submit">
Post it
</button>
<a href="#allposts">
<button type="button" class="btn btn-primary" >
Go back to post list
</button></a>
<br>
<uib-alert
ng-repeat="alert in alerts"
type="{{alert.type}}"
dismiss-on-timeout="5000"
close="alerts.splice($index, 1);">{{alert.msg}}
</uib-alert> </form>
</script>
<div ng-view></div>
<script src="app.js"></script>
</body>
and JS:
Array.prototype.collate = function(collateSize) {
var collatedList = [];
if (collateSize <= 0) {
return [];
}
angular.forEach(this, function(item, index) {
if (index % collateSize === 0) {
collatedList[Math.floor(index / collateSize)] = [item];
} else {
collatedList[Math.floor(index / collateSize)].push(item);
}
});
return collatedList;
};
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'allposts.htm',
controller: 'PostsController'
}).when('/posts', {
templateUrl: 'posts.htm',
controller: 'PostController'
}).when('/addpost', {
templateUrl: 'addpost.htm',
controller: 'AddController'
}).otherwise({
redirectTo: '/'
});
});
myApp.controller('PostsController', function($scope) {});
myApp.controller('PostController', function($scope) {});
myApp.controller('AddController', function($scope) {});
myApp.controller('controller', function($scope, $http) {
$scope.apptitle = "My app";
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts"
}).then(function(response) {
$scope.posts = response.data;
$scope.viewby = 9;
$scope.totalItems = $scope.posts.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5;
$scope.collatedPosts = getCollatedPosts($scope.posts);
$scope.newPost = {};
function getCollatedPosts(posts) {
if (!posts) {
return [];
}
var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
return paginatedPosts.collate(3);
}
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.addPost = function(){
$http.post("http://jsonplaceholder.typicode.com/posts",{
title: $scope.newPost.title,
body: $scope.newPost.body,
usrId: 1
})
.success(function(data, status, headers, config){
console.log(data);
$scope.posts.push($scope.newPost);
$scope.newPost = {};
})
.error(function(error, status, headers, config){
console.log(error);
});
};});
$scope.alerts = [];
$scope.msg = "Well done! Your post was added";
$scope.addAlert = function(msg, type) {
$scope.alerts.push({
msg: msg,
type: type
});
};
});
My code is not working. There is 100 ng-repeated posts and I want each post title to link to the post view. Current code links every title to #/posts. I also tried {{post.title}}, but with no success.
What is the correct way to do this?
You can see full code here:

Do following changes::
Codepen :http://codepen.io/ruhul/pen/mAJLEo
1) Remove "/" from your href and use post.id (I believe on a click of link, you will be doing some of the database calls based on postID and will render it to UI ).
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList track by $index"> <div class="inner"> {{post.title}} <p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p> </div>
2) As you are passing parameter add your routing configuration as below::
You can later use this parameter in controller using $routeParams.
.when('/posts/:postId', { templateUrl: 'posts.htm', controller: 'PostController' })
3) Change your controller to this::
myApp.controller('PostController', function($scope,$routeParams,$http) {
console.log($routeParams.postId)
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts/"+$routeParams.postId
}).then(function(response) {$scope.post=response.data});
});

Related

Ng-View is not give the output "RangeError: Maximum call stack size exceeded"

Ng-View is not give the output . Trying to route form one page to another by page instead i getting this error .
"RangeError: Maximum call stack size exceeded"
Kindly check the following and give your suggestion to overcome that .
App.jss
'use strict';
var app = angular.module('Sab', ['ui.filters','ui','ngRoute'])
.config(["$routeProvider", function($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'index.html',
controller: 'menuCtrl'
}).
when('/Deals/:offer_name', {
templateUrl: 'Deals.html',
controller: 'abCtrl'
}).
when('/D', {
templateUrl: 'D.html',
}).
otherwise({
redirectTo: '/home'
});
}])
.controller('menuCtrl', function($scope,$http) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
$scope.myData = response.data;
$scope.offerName = ''; //set initially
$scope.selectedIndex = -1;
$scope.filteredOffers = [];
});
$scope.showData = function(offer_name, index) {
$scope.offerName = offer_name;
$scope.filteredOffers = $scope.myData.filter(function(offer) {
return offer.offer_name == $scope.offerName;
});
$scope.selectedIndex = index;
}
})
.controller('abCtrl',function($scope,$http,$stateParams,$filter,$window) {
$http.get("http://tools.vcommission.com/api/coupons.php?apikey=e159f64e3dd49fddc3bb21dcda70f10c6670ea91aac30c7cb1d4ed37b20c45b8").then(function (response) {
var offerName = $stateParams.offer_name;
$scope.filteredOffers = $filter('filter')(response.data, {offer_name: offerName});
// $scope.filteredOffers = _.filter(response.data, ["offer_name",offerName]);
console.log($scope.filteredOffers)
console.log(offerName)
$scope.dealopen = function($a){
for (var i=0;i<response.data.length;i++)
{
//console.log($scope.data[i].name);
$link=response.data[i].link;
if ($link==$a)
{
$window.open($link,"_self","location=yes");
console.log($a);
}
}
}
});
});
Html
<div class="row" ng-app="Sab" ng-controller="menuCtrl" >
<ng-view></ng-view>
<div class="col col-100 " ng-repeat="da in myData | unique: 'store_image'" >
<div class="card col " >
<img class=" img-responsive " ng-src="{{ da.store_image}}"
ng-click="showData(da.offer_name, $index)"
/>
<div class="caption">
<a class="item item-text-wrap" href="#/Deals/{{da.offer_name }}" ng-click="showData(da.offer_name, $index)"
>
<b class="group inner list-group-item-heading center-block">
{{da.category }} Deals </b>
</a>
</div>
</div>
</div>
</div>
</div>
First, which comes to mind - infinite recursion. First of all, your menuCtrl is loaded two times:
In html
ng-controller="menuCtrl"
In route
when('/home', {
templateUrl: 'index.html',
controller: 'menuCtrl'
})
Let's start from fixing this. The next depends, I think on your other html templates.

$http POST request only returning one of the values in Angular

I'm creating an app in which one of the views contains a form that should add a post. I'm using the fake JSONplaceholder API. The resources are not really created on the server but it is faked as if. I'm using console.log to return the title and body of the post I'm creating, but only an ID shows in the console, like so: Object {id: 101}
Here's my code:
<body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
<h1>{{apptitle}}</h1>
<script type="text/ng-template" id="allposts.htm">
<a href="#addpost">
<button type="button" class="btn btn-primary" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Add a post
</button>
</a>
View
<select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
<option>9</option>
<option>18</option>
<option>36</option>
<option>100</option>
</select>posts
<div class="row" ng-repeat="collatedPostList in collatedPosts">
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
<div class="inner">
{{post.title}}
<hr>
<p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
</div>
</div>
</div>
<div class="text-center">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
</div>
</script>
<script type="text/ng-template" id="post.htm">
</script>
<script type="text/ng-template" id="addpost.htm">
<form ng-submit="submit()" class="adding">
<input id="titleadd" type="text" name="title" ng-model="title" placeholder="Add title">
<br>
<input id="textadd" type="text" name="body" ng-model="body" placeholder="Add some text">
<br>
<button type="submit" class="btn btn-primary" id="submit" value="Submit">
Post it
</button>
<a href="#allposts">
<button type="button" class="btn btn-primary" >
Go back to post list
</button></a>
</form>
</script>
<div ng-view></div>
<script src="app.js"></script>
</body>
JS:
Array.prototype.collate = function(collateSize) {
var collatedList = [];
if (collateSize <= 0) {
return [];
}
angular.forEach(this, function(item, index) {
if (index % collateSize === 0) {
collatedList[Math.floor(index / collateSize)] = [item];
} else {
collatedList[Math.floor(index / collateSize)].push(item);
}
});
return collatedList;
};
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'allposts.htm',
controller: 'PostsController'
}).when('/post', {
templateUrl: 'post.htm',
controller: 'PostController'
}).when('/addpost', {
templateUrl: 'addpost.htm',
controller: 'AddController'
}).otherwise({
redirectTo: '/'
});
});
myApp.controller('PostsController', function($scope) {});
myApp.controller('PostController', function($scope) {});
myApp.controller('AddController', function($scope) {});
myApp.controller('controller', function($scope, $http) {
$scope.apptitle = "Kansi app";
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts"
}).then(function(response) {
$scope.posts = response.data;
$scope.viewby = 9;
$scope.totalItems = $scope.posts.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5;
$scope.collatedPosts = getCollatedPosts($scope.posts);
});
$scope.submit = function(){
$http({
method:'POST',
url:"http://jsonplaceholder.typicode.com/posts",
data : {
title: $scope.title,
body: $scope.body
},
headers: {
'Content-Type': 'application/json'
}
})
.success(function(response){
$scope.result = response;
console.log($scope.result);
})
.error(function(){
console.log("error");
});
};
function getCollatedPosts(posts) {
if (!posts) {
return [];
}
var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
return paginatedPosts.collate(3);
}
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
});
Network:
There are no errors in the console. Why only the id is returning?
Though the screenshot is truncated, it is clearly seen that Request payload is empty object. So it doesn't send title and body fields, it doesn't receive them.
Angular can't just discard data object for no reason. It serializes it with JSON.stringify. title and body object properties (equal to $scope.title and $scope.body respectively) can be omitted on one condition. This happens if they are undefined.

call a controller inside another controller Angularjs

I have declared two HTML pages in my index: Home.html and jargon.html.
Each page has its own controller loaded in the application module.
angular.module('starter', ['ionic', 'ngRoute', 'starter.homeController', 'starter.jargonController'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'templates/home.html',
controller: 'homeCtrl'
})
.state('jargon', {
url: 'jargon',
templateUrl: 'templates/jargon.html',
controller: 'jargonCtrl'
});
$urlRouterProvider.otherwise('/home');
});
My problem is that jargon.html has two other controllers:
<ion-view title="Jargon">
<ion-content>
<a class="item" href="#/jargon"></a>
<ion-pane ng-controller="CardsCtrl">
<div class="testimage">
<img ng-src="img/Logo.png" class="logo">
</div>
<swipe-cards on-card-swipe="onSwipe($event)">
<swipe-cards>
<swipe-card on-card-swipe="cardSwiped()" id="start-card">
</swipe-card>
<swipe-card ng-repeat="card in cards" on-destroy="cardDestroyed($index)" on-card-swipe="cardSwiped($index)">
<div ng-controller="CardCtrl">
<div class="image">
<img ng-src="{{card.image}}">
</div>
<div class="title">
{{card.Description}}
</div>
</div>
</swipe-card>
</swipe-cards>
</ion-pane>
</ion-content>
Controllers to manipulate the cards:
.controller('CardsCtrl', function($scope, $ionicSwipeCardDelegate) {
var cardTypes = [
{ image: 'img/cards/ASE card.png' },
{ image: 'img/cards/MCR-card.png' },
{ image: 'img/cards/R2A card.png' },
{ image: 'img/cards/RRH card.png' }];
$scope.cards = Array.prototype.slice.call(cardTypes, 0, 0);
//intialisation premiere carte
var newCard = cardTypes[0];
newCard.id = Math.random();
$scope.cards.push(angular.extend({}, newCard));
$scope.cardSwiped = function(index) {
$scope.addCard();
};
$scope.cardDestroyed = function(index) {
$scope.cards.splice(index, 1);
};
$scope.addCard = function() {
var newCard = cardTypes[Math.floor(Math.random() * cardTypes.length)];
newCard.id = Math.random();
$scope.cards.push(angular.extend({}, newCard));
}
})
.controller('CardCtrl', function($scope, $ionicSwipeCardDelegate) {
$scope.goAway = function() {
var card = $ionicSwipeCardDelegate.getSwipeableCard($scope);
card.swipe();
};
});
My question is: Where can I call both CardsCtrl and CardCtrl ? In the same jargonController.js file?
Here is a simple example:
<div ng-controller="HelloCtrl">
<p>{{fromService}}</p>
</div>
<br />
<div ng-controller="GoodbyeCtrl">
<p>{{fromService}}</p>
</div>
JavaScript:
//angular.js example for factory vs service
var app = angular.module('myApp', []);
app.service('testService', function(){
this.sayHello= function(text){
return "Service says \"Hello " + text + "\"";
};
this.sayGoodbye = function(text){
return "Service says \"Goodbye " + text + "\"";
};
});
function HelloCtrl($scope, testService)
{
$scope.fromService = testService.sayHello("World");
}
function GoodbyeCtrl($scope, testService)
{
$scope.fromService = testService.sayGoodbye("World");
}
http://jsfiddle.net/Ne5P8/2701/

AngularJS with UI-Route and Master Detail

I'm trying to get JSON data from my server and display them into my website. I am using Ui-router extension. What I am looking for here is a master-detail setup.
Index.html
<input ng-model="manga.name" ng-change="searchManga()" id="search" type="search" placeholder="Manga İsmi Girin..." required>
<div class="row" ui-view="viewA">
<div class="col s8 offset-s1" ng-controller = "nbgCtrl">
<div class="row">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="ui-sref="#/manga/{{manga.id}}"" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
</div>
<div class="col s7">
<p>{{manga.ad}}</p>
<a href="" class="waves-effect waves-light btn">
</a>
I have above a main page and repeating some thumbnails. Every thumbnail links to its detailed information page. And when clicking a thumbnail it has to carry its own data and load it here. Here's what I've got so far:
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('list', {
url: "/",
controller: "ListCtrl",
templateUrl: "index.html",
}
)
$stateProvider
.state('icerik', {
url: "/icerik/:{{mangaid}}",
controller: "mmgCtrl",
views: {
"viewA": { templateUrl: "icerik.html" },
}
}
)
})
.factory('Mangas', function($http){
var factory = {};
function getData(manganame, callbak) {
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
$http.get(url).success(function(data){
factory = data.results;
callback(data.results);
})
}
return {
list: getData,
find: function(name, callback) {
console.log(name);
var manga = cachedData.filter(function(entry) {
return entry.id == name;
})[0];
callback(manga);
}
};
})
.controller('ListCtrl', function($scope, $http, Mangas) {
$scope.manga = {
name: '' }
$scope.searchManga = function() {
Mangas.list($scope.manga.name, function(mangas) {
$scope.mangas = mangas;
});
}
})
.controller('mmgCtrl', function($scope, $http, $stateParams, Mangas) {
Mangas.find($stateParams.mangaid, function(manga) {
$scope.manga = manga;
});
})
I just doubt that the getData is not a promise in resolve closure you hava returned MY.isimler.then so in mmgCtrl controller first console getData to make sure it's a promise or data

How to add multiple dependencies using angular.module and Angular Material

I'm having an issue with Angular Material where my forms/inputs and buttons don't show up.
I'm guessing it's because I havent added ngMaterial as a dependency. When I do, it breaks my code.
this is my original app.js file:
angular.module('myApp', ['ngRoute',])
.config( [
'$compileProvider',
function( $compileProvider ) {
var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0,-1)
+ '|chrome-extension:'
+currentImgSrcSanitizationWhitelist.toString().slice(-1);
console.log("Changing imgSrcSanitizationWhiteList from "+currentImgSrcSanitizationWhitelist+" to "+newImgSrcSanitizationWhiteList);
$compileProvider.imgSrcSanitizationWhitelist(newImgSrcSanitizationWhiteList);
}
])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
controller: 'MainCtrl'
})
.when('/settings', {
templateUrl: 'templates/settings.html',
controller: 'SettingsCtrl'
})
.otherwise({redirectTo: '/'});
})
.provider("Weather", function () {
var apiKey = "";
this.setApiKey = function (key) {
if (key) {
this.apiKey = key;
}
};
this.getUrl = function (type, ext) {
return "http://api.wunderground.com/api/" + this.apiKey + "/" + type +
"/q/" + ext + ".json";
};
this.$get = function ($q, $http) {
var self = this;
return {
getWeatherForecast: function (city) {
var d = $q.defer();
$http({
method: "GET",
url: self.getUrl("forecast", city),
cache: true
}).success(function (data) {
// forecasts are nested inside forecast.simpleforecast
// console.log(data);
d.resolve(data.forecast.simpleforecast);
}).error(function (error) {
d.reject(error);
});
return d.promise;
}
};
};
})
.config(function(WeatherProvider) {
WeatherProvider.setApiKey('7b78fc434225f02f');
})
.controller('MainCtrl',
function($scope, $timeout, Weather){
//build date object
$scope.date = {};
// Update function
var updateTime = function() {
$scope.date.raw = new Date();
$timeout(updateTime, 1000);
}
// Kick off the update function
updateTime();
$scope.weather = {};
Weather.getWeatherForecast("IL/Chicago")
.then(function (data) {
$scope.weather.forecast = data;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!doctype html>
<html data-ng-app="myApp" data-ng-csp="">
<head>
<meta charset="UTF-8">
<title>Weathim</title>
<link rel="stylesheet" href="css/angular-material.min.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="themes/teal-theme.css">
<link href='http://fonts.googleapis.com/css?family=Rajdhani|Dosis:400,700|Raleway:400,100,300|Advent+Pro' rel='stylesheet' type='text/css'>
</head>
<body ng-controller="MainCtrl" md-theme="teal">
<md-toolbar flex="100" flex-order="1">
<div class="md-toolbar-tools">
<h2>
<span>{{ date.raw | date:'EEEE MMMM yyyy' }}</span>
</h2>
<span flex></span>
<md-button class="md-icon-button" aria-label="Settings">
<md-icon><img src="imgs/settings.png"></md-icon>
</md-button>
</div>
</md-toolbar>
<div class="container">
<md-content layout="row" layout-align="center">
<div id="datetime">
<div class="time">{{ date.raw | date:'hh:mm' }}</div><div class="sec">{{ date.raw | date:'ss' }}</div>
<div class="day"></div>
</div>
</md-content>
<div layout="row" layout-sm="column">
<md-content class="bg1" ng-repeat="day in weather.forecast.forecastday" id="forecast">
<div ng-class="{today: $index == 0}">
<div flex="25">
<md-toolbar class="md-warn">
<div class="md-toolbar-tools" layout-align="center">
<h2 class="md-flex" ng-if="$index == 0">Now</h2>
<h2 class="md-flex" ng-if="$index != 0">{{ day.date.weekday }}</h2>
</div>
</md-toolbar>
<div class="infocontent" layout layout-align="center">
<img class="{{ day.icon }}" ng-src="imgs/{{ day.icon }}.png"/>
</div>
<div layout="row">
<div flex class="low">
Low: <span class="temp" layout layout-align="center">{{ day.low.fahrenheit }}</span>
</div>
<div flex class="high">
High: <span class="temp" layout layout-align="center">{{ day.high.fahrenheit }}</span>
</div>
</div>
<md-toolbar class="md-warn border">
<div class="md-toolbar-tools" layout-align="center">
<h2 class="md-flex">{{ day.conditions }}</h2>
</div>
</md-toolbar>
</div>
</div>
</md-content>
</div>
<md-content md-theme="docs-dark" layout-padding layout="row" layout-sm="column">
<input ng-model="" placeholder="Placeholder text"><md-button class="md-raised md-primary">Primary</md-button>
</md-content>
</div>
<script src="./js/vendor/angular.min.js"></script>
<script src="./js/vendor/angular-route.min.js"></script>
<script src="./js/vendor/angular-material.min.js"></script>
<script src="./js/vendor/angular-animate.min.js"></script>
<script src="./js/app.js"></script>
</body>
</html>
i attempted to add multiple dependencies but it just broke my code:
angular.module('myApp', [
'ngRoute',
'ngMaterial'
]).config(function($mdThemingProvider) {
$mdThemingProvider.theme('teal')
.primaryPalette('teal')
.accentPalette('orange');
})
.config( [
'$compileProvider',
function( $compileProvider ) {
var currentImgSrcSanitizationWhitelist = $compileProvider.imgSrcSanitizationWhitelist();
var newImgSrcSanitizationWhiteList = currentImgSrcSanitizationWhitelist.toString().slice(0,-1)
+ '|chrome-extension:'
+currentImgSrcSanitizationWhitelist.toString().slice(-1);
console.log("Changing imgSrcSanitizationWhiteList from "+currentImgSrcSanitizationWhitelist+" to "+newImgSrcSanitizationWhiteList);
$compileProvider.imgSrcSanitizationWhitelist(newImgSrcSanitizationWhiteList);
}
])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/home.html',
controller: 'MainCtrl'
})
.when('/settings', {
templateUrl: 'templates/settings.html',
controller: 'SettingsCtrl'
})
.otherwise({redirectTo: '/'});
})
.provider("Weather", function () {
var apiKey = "";
this.setApiKey = function (key) {
if (key) {
this.apiKey = key;
}
};
this.getUrl = function (type, ext) {
return "http://api.wunderground.com/api/" + this.apiKey + "/" + type +
"/q/" + ext + ".json";
};
this.$get = function ($q, $http) {
var self = this;
return {
getWeatherForecast: function (city) {
var d = $q.defer();
$http({
method: "GET",
url: self.getUrl("forecast", city),
cache: true
}).success(function (data) {
// forecasts are nested inside forecast.simpleforecast
// console.log(data);
d.resolve(data.forecast.simpleforecast);
}).error(function (error) {
d.reject(error);
});
return d.promise;
}
};
};
})
.config(function(WeatherProvider) {
WeatherProvider.setApiKey('7b78fc434225f02f');
})
.controller('MainCtrl',
function($scope, $timeout, Weather){
//build date object
$scope.date = {};
// Update function
var updateTime = function() {
$scope.date.raw = new Date();
$timeout(updateTime, 1000);
}
// Kick off the update function
updateTime();
$scope.weather = {};
Weather.getWeatherForecast("IL/Chicago")
.then(function (data) {
$scope.weather.forecast = data;
});
});
any help would be appreciated

Categories

Resources