call a controller inside another controller Angularjs - javascript

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/

Related

AngularJS To Do Application. Problem with edit button

I'm trying to create To Do List app with ui-router. I can create task, delete but i cannot edit my task because of this problem. Can anyone help me?
Transition Rejection($id: 2 type: 6, message: The transition errored, detail: Error: Transition Rejection($id: 1 type: 4, message: This transition is invalid, detail: The following parameter values are not valid for state 'second': [todoText:undefined]))
var app = angular.module('app', [
'ui.router',
'todoApp.services',
'todoApp.controllers'
]);
app.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('first', {
url: '/new',
templateUrl: 'detail.html',
controller: 'CreateCtrl'
})
.state('second', {
url: '/edit/:todoText',
controller: 'EditCtrl',
templateUrl: 'detail.html'
})
.state('third', {
url: '/',
controller: 'ListCtrl',
templateUrl: 'list.html'
})
.state('root', {
controller: 'ListCtrl',
templateUrl: 'list.html'
})
}]);
app.controller('EditCtrl', function ($scope, $location, $stateParams, Todos) {
$scope.todos = Todos;
var result = $scope.todos.filter(function (obj) {
return obj.text == $stateParams.todoText;
}); console.log(result);
$scope.todoText = result[0].text;
$scope.todoDetails = result[0].details;
$scope.todoDate = result[0].date;
console.log(result);
$scope.save = function () {
var text = $scope.todoText;
var details = $scope.todoDetails;
var done = $scope.todoDone;
var date = $scope.todoDate;
alert(text);
angular.forEach($scope.todos, function (todo) {
if (todo.text == text) {
todo.text = text;
todo.details = details;
todo.date = date;
}
});
$location.path('/');
};
});
app.factory('Todos', function () {
var items = [
]
return items;
});
<!-- html button -->
<button class="btn btn-light">
<a ui-sref='second()'>
<i class="fas fa-edit"></i>Edit</i>
</a>
</button>
You have a state second that expects a parameter todoText:
.state('second', {
url: '/edit/:todoText',
controller: 'EditCtrl',
templateUrl: 'detail.html'
})
The problem is that when you call that state you don't pass any parameter:
<a ui-sref='second()'>
Here you need to add the todoText parameter like this:
<a ui-sref='second({todoText: todo.text})'>
#Bill P helped. Thank you.
<a ui-sref='second({todoText: todo.text})'>

AngularJS - how to get an ngRepeat filtered result reference inside controller

I am using an ng-repeat directive with filter like so:
<tr ng-repeat="entry in (filteredEntries = (entries | filter:hasGroup | filter:readingFilter | orderBy:data.sortType:data.sortReverse:true))"></tr>
<span>{{filteredEntries.length}}</span>
I'm using $stateProvider to load views and controllers
$stateProvider
.state('welcome', {
url: "/",
templateUrl: viewsPrefix + "welcome.html",
data: {
pageTitle: 'Welcome'
},
controller: "WelcomeCtrl"
})
.state('data', {
url: "/data",
templateUrl: viewsPrefix + "data.html",
data: {
pageTitle: 'Data'
},
controller: "DataCtrl",
})
Here is a snippet from my controller:
.controller('DataCtrl', ['$scope', '$rootScope', '$state', '$translate', '$filter') {
$scope.filteredEntries = [];
$scope.entries = [1, 2, 3, 4, 5, 6,7];
$scope.hasGroup = function(){return true;}
$scope.readingFilter = function(){return true;}
setInterval(function () {
console.log($scope.filteredEntries);
}, 500);
});
There is no problem with such a code, however I need to access filteredEntries attribute in my controller using $scope.filteredEntries which should be ok with no problem. Unfortunately this didn't work and I couldn't figure it out why this is happening.
You can access the filtered array in BOTH VIEW AND CONTROLLER using this method:
var app = angular.module('test', []);
app.controller('MainCtrl', function() {
var vm = this;
vm.people = ['fox', 'rosi', 'err3', 'rob', 'cesar', 'geoff'];
vm.logPeople = function() {
console.log("FILTERED PEOPLE: ", vm.filteredPeople);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="test">
<div ng-controller="MainCtrl as vm">
<h2>List of people</h2>
Search: <input type="text" ng-model="search">
<ul>
<li ng-repeat="person in vm.filteredPeople = (vm.people | filter:search)">
{{person}}
</li>
</ul>
<p ng-hide="vm.filteredPeople.length">There is no result</p>
<button ng-click="vm.logPeople()">LOG PEOPLE</button>
<br><br>
Number of filtered people: {{vm.filteredPeople.length}}
</div>
</div>
Updated for your example with updated code.
So, in your state provider for the data route, add "controllerAs: 'vm',":
.state('data', {
url: "/data",
templateUrl: viewsPrefix + "data.html",
data: {
pageTitle: 'Data'
},
controllerAs: 'vm',
controller: "DataCtrl",
})
Then, in your controller:
.controller('DataCtrl', ['$scope', '$rootScope', '$state', '$translate', '$filter') {
var vm = this;
vm.filteredEntries = [];
vm.entries = [1, 2, 3, 4, 5, 6,7];
vm.hasGroup = function(){return true;}
vm.readingFilter = function(){return true;}
vm.logEntries = function() {
console.log("FILTERED Entries: ", vm.filteredEntries);
}
});
And finally, in your template (added button to test logging entries):
{{filteredEntries.length}}
<button ng-click="vm.logEntries()">LOG Entries</button>
<br><br>

using modal from directive in IonicFramework

I have a directive that shows modal window after loading data:
.directive('nwAssets', function () {
return {
restrict: 'A',
templateUrl: 'app/dashboard/templates/nw-assets.html',
controller: controller,
scope: {
assets: '=nwAssets'
}
};
function controller($scope, $ionicModal, NwPath) {
$scope.pathToThumb = NwPath.toThumb;
$scope.pathToSrc = NwPath.toSrc;
$scope.fileName = NwPath.fileName;
$ionicModal.fromTemplateUrl('app/dashboard/templates/nw-modal.html', {
scope: $scope,
animation: 'slide-in-down'
}).then(function (modal) {
$scope.modal = modal;
});
$scope.openModal = function (src, fileName) {
$scope.pathToSrc = src;
$scope.fileName = fileName;
$scope.modal.show();
};
$scope.closeModal = function () {
$scope.modal.hide();
};
}
});
Factory I used:
.factory('NwPath', function (baseUrl) {
return {
toThumb: toThumb,
toSrc: toSrc,
fileName: fileName
};
function toThumb(asset) {
return baseUrl + '/uploads/file/' + asset.guid + '/' + assetThumbFileName(asset);
}
function toSrc(asset) {
return baseUrl + '/uploads/file/' + asset.guid + '/' + asset.file_name;
}
function assetThumbFileName(asset) {
var fileNames = asset.file_name.split('.');
fileNames[0] = fileNames[0] + '_pi_200x200';
return fileNames.join('.');
}
function fileName (asset) {
return asset.file_name;
}
});
Template where I call modal:
<div ng-repeat="asset in assets">
<img ng-if="asset.mime_type.indexOf('image') === 0"
ng-src="{{pathToThumb(asset)}}"
ng-click="openModal(pathToSrc(asset), fileName(asset))"
alt="" />
Template where modal closes:
<ion-modal-view>
<ion-header-bar class="bar bar-header bar-positive">
<h1 class="title">{{fileName}}</h1>
<div class="buttons">
<button class="button button-clear" ng-click="closeModal()">Close</button>
</div>
</ion-header-bar>
<ion-content class="text-center">
<img ng-src="{{pathToSrc}}" alt="" />
</ion-content>
It works just once: modal opens, abd data shows. But after modal is closed, it won't be shown next time and shows an error: "v6.pathToSrc is not a function"
Please help )

UI-Router $stateParams With Master Detail Pattern

I need a Master Detais pattern for my web site. In index lots of thumbnails and every thumbnail link to their detailed page. I make a progress but does not get to work. Its load thumbnails on index oage but when I click to thumbnails its load blank page.
Index:
<body ui-view="viewA">
<div class="row" ui-view="viewB">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerikDetails({id:manga.id})" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: "/",
views: {
"viewA": { templateUrl: "index.html",
controller: "indexCtrl",}
}})
$stateProvider
.state('icerik', {
url: "/icerik",
views: {
"viewB": { templateUrl: "icerik.html",
controller: "mmgCtrl",},
}})
$stateProvider
.state('icerikDetails', {
url: "/icerik/:id",
template: "<div>{{details }}</div>",
controller: "mmgCtrl",
resolve: {
getData : function(MY, $stateParams, $filter){
return MY.isimler.then(function(res){
return $filter('filter')(res.data, {id: $stateParams.id}, true)[0];
});}
}
})
$urlRouterProvider.otherwise("/");
})
factory and controllers:
.factory('MY', function($http){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen){
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
$scope.manga = getData.then(function(data){
$scope.details = data;
});})
I am not sure what you are trying to achieve, but at least I tried to convert your snippets into something working.
There is a working example
To get more understanding, do read these:
Nested States and Nested Views
Multiple Named Views
These are states, with a hiererchy. Index is super root, and details is super child:
$stateProvider
.state('index', {
url: "/",
views: {
"": {
templateUrl: "index.tpl.html",
controller: "indexCtrl",
}
}
})
.state('icerik', {
parent: "index",
url: "^/icerik",
views: {
"viewA": {
templateUrl: "icerik.html",
controller: "indexCtrl",
},
}
})
.state('icerik.icerikDetails', {
url: "/icerik/:id",
template: "<div>{{manga}}</div>",
controller: "mmgCtrl",
resolve: {
getData: function(MY, $stateParams, $filter) {
return MY.isimler.then(function(res) {
return $filter('filter')(res.data, {
id: $stateParams.id
}, true)[0];
});
}
}
})
$urlRouterProvider.otherwise("/");
These will be new controllers and factory:
.factory('MY', function($http) {
var factory = {};
//var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var url = 'data.json';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen) {
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
//$scope.manga = getData.then(function(data){
// $scope.details = data;
// });
$scope.manga = getData;
})
And an example of templates "index.tpl.html":
<div >
<h2> this is index view</h2>
icerik
<div ui-view="viewA"></div>
</div>
and "icerik.html":
<div class="row" >
<div class="col s12 m6 l4" ng-repeat="manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerik.icerikDetails({id:manga.id})" class="thumbnail">
img src="/kapaklar/{{manga.kapak}}"
</a>
</div>
</div>
</div>
<hr>
<div ui-view=""></div>
</div>
Check it here

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