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
Related
Could you please let me know what is wrong with my code? I get the initial HTML page, but when I click on "Open", nothing happens. Not even the console logs an error, or any other change.
app.js
var app = angular.module('carApp', ['ui.bootstrap']);
ctrl.js
app.controller('carCtrl', function($scope, $http, $uibModal) {
$http.get('jobs.json').success(function(data) {
$scope.data = data;
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller : modalContentCtrl,
resolve: {
items: function() {
return $scope.data;
}
}
})
}
});
});
var modalContentCtrl = function ($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
};
JSON:
{
"specs":[
{
"job-title":"TITLE",
"job-apply":"applink",
"job-body":"JOB BODY"
}
]
}
HTML:
<div class="car-up">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="item in data">{{item}}</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
I'm new to AngularJS, but I have linked the app.js and ctrl.js... thanks.
EDIT: after I've placed ng-controller="carCtrl" in the html file, I receive this error:
Error: [$injector:unpr]
http://errors.angularjs.org/1.5.7/$injector/unpr?p0=%24modalInstanceProvider%20%3C-%20%24modalInstance
O/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:6:412
db/n.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:84
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
db/V<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:144
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:78
h/<.invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:163
gf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:89:397
resolveSuccess#https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.2.0/ui-bootstrap-tpls.js:4422:34
e/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:130:409
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:103
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:142:165
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:399
Lc[b]https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:274:444
Sf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:37:31
Rf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:36:486
Please find working demo
angular.module('carApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
var app = angular.module('carApp');
app.controller('carCtrl', function($scope, $http, $uibModal) {
//$http.get('jobs.json').success(function(data) {//Uncomment
//$scope.data = data; Uncomment
//Remove below line from code when you are using this in your project
$scope.data = {
"specs": [{
"job-title": "TITLE",
"job-apply": "applink",
"job-body": "JOB BODY"
}]
}
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
resolve: {
items: function() {
return $scope.data;
}
}
})
}
//});//Uncomment
});
app.controller('ModalInstanceCtrl', function($uibModalInstance, items, $scope) {
$scope.data = items;
console.log($scope.data);
$scope.selected = {
item: $scope.data.specs
};
});
<!doctype html>
<html ng-app="carApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="carCtrl" class="modal-demo">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="(k,v) in data.specs">
<span>Title: {{v["job-title"]}}<br/> </span>
<span>Link: {{v["job-apply"]}}<br/> </span>
<span>Body: {{v["job-body"]}}<br/> </span>
</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
</body>
</html>
Try defining the controller like this outside,
app.controller('modalContentCtrl ', function($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
}
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});
});
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.
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/
I am new to angular. I have tried creating an application and all was going well until I decided to create a custom directive.
My html looks like this:
<body ng-app="sapphireApp">
<div class="off-canvas-wrap" data-offcanvas>
<div class="inner-wrap">
<nav class="tab-bar">
<section class="middle tab-bar-section">
<h1 class="title">Sapphire</h1>
</section>
<section class="right-small">
<a class="right-off-canvas-toggle menu-icon" href="#"><span></span></a>
</section>
</nav>
<aside class="right-off-canvas-menu" ng-controller="TopController as topController">
<ul class="off-canvas-list">
<li><label>Users</label></li>
<li ng-hide="topController.userService.isLoggedIn">Login</li>
<li ng-show="topController.userService.isLoggedIn">Logout</li>
</ul>
</aside>
<section class="main-section" ng-view></section>
<a class="exit-off-canvas"></a>
</div>
</div>
<script src="scripts/angular.min.js"></script>
<script src="scripts/mm-foundation/mm-foundation-0.5.1.min.js"></script>
<script src="scripts/angular-cookies.min.js"></script>
<script src="scripts/angular-route.min.js"></script>
<script src="scripts/angular-touch.min.js"></script>
<script src="scripts/app/app.js"></script>
<script src="scripts/app/controllers.js"></script>
<script src="scripts/app/services.js"></script>
<script src="scripts/app/directives.js"></script>
</body>
and my four angularJS files look like this respectively:
app.js
angular.module('sapphireApp', ['ngRoute', 'ngCookies', 'ngTouch', 'mm.foundation'])
.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home/index.html'
})
.when('/login', {
templateUrl: 'views/account/login.html'
})
$routeProvider.otherwise({
redirectTo: '/'
});
});
controllers.js
angular.module('sapphireApp')
.controller('TopController', ['UserService',
function (UserService) {
var self = this;
self.userService = UserService;
// Check if the user is logged in when the application
// loads
// User Service will automatically update isLoggedIn
// after this call finishes
UserService.session();
}
])
.controller('HomeController',
function () {
var self = this;
}
)
.controller('LoginController', ['UserService', '$location',
function (UserService, $location) {
var self = this;
self.user = { username: '', password: '' };
self.login = function () {
UserService.login(self.user).then(function (success) {
$location.path('/');
}, function (error) {
self.errorMessage = error.data.msg;
})
};
}
]);
services.js
angular.module('sapphireApp')
.factory('UserService', ['$http', '$cookieStore', function ($http, $cookieStore) {
var service = {
isLoggedIn: false,
session: function () {
var user = $cookieStore.get('user');
if (user)
service.isLoggedIn = true;
return user;
},
login: function (user) {
return $http.post('/api/account/login', user)
.then(function (response) {
service.isLoggedIn = true;
$cookieStore.put('user', response);
return response;
});
}
};
return service;
}]);
directives.js
angular.module('sapphireApp')
.directive('square', function () {
return {
restrict: 'E',
template: '<div class="square"><h1>Show something else</h1></div>',
link: function () {
alert("this is working");
}
};
});
The login view works fine, but the home view doesn't. It looks like this:
<div class="row" ng-controller="HomeController as homeController">
<div class="small-2 columns">
<sqaure>
<h1>This is the square</h1>
</sqaure>
</div>
</div>
Now, because I have created the directive square and set it to be an element, I would expect an output like this:
<sqaure>
<div class="square">
<h1>Show something else</h1>
</div>
</sqaure>
and I would also expect there to be an alert. But I get nothing. No errors and the Html stays unmodified.
Can anyone tell me why? I assume because I am getting no errors, it is just a misunderstanding on my part.
You have a typo in the directive:
<sqaure> //typo here
<h1>This is the square</h1>
</sqaure> //typo here
Change sqaure to square.