I'm new to angular js. I was trying to save and share the scope of two different controllers.
Below is my script and views.
script.js:
var app = angular.module('app', ['ngRoute']);
app.run(function ($rootScope) {
$rootScope.$on('scope.stored', function (event, data) {
console.log("scope.stored", data);
});
});
app.controller('FirstController', function($scope) {
$scope.counter = 0;
$scope.add = function(amount) { $scope.counter += amount; };
$scope.subtract = function(amount) { $scope.counter -= amount; };
});
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/v1', {
templateUrl: 'views/v1.ejs',
controller: 'controller1'
}).
when('/v2', {
templateUrl: 'views/v2.ejs',
controller: 'controller2'
})
}]);
app.controller('controller1', function($scope,Scopes) {
Scopes.store('controller1',$scope);
$scope.data = "controller1";
$scope.buttonClick = function () {
console.log( Scopes.get('controller2').data);
};
});
app.controller('controller2', function($scope,Scopes) {
Scopes.store('controller2',$scope);
$scope.data = "controller2";
$scope.buttonClick = function () {
console.log( Scopes.get('controller1').data);
};
});
app.factory('Scopes', function ($rootScope) {
var mem = {};
return {
store: function (key, value) {
$rootScope.$emit('scope.stored', key);
mem[key] = value;
},
get: function (key) {
return mem[key];
}
};
});
index.html:
<!doctype html>
<html ng-app="app">
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/script.js"> </script>
</head>
<body>
<a href='#v1'>View1</a>
<a href='#v2'>View2</a>
<div ng-view>
</div>
</body>
</html>
v1.ejs:
<div ng-controller="controller1">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
v2.ejs:
<div ng-controller="controller2">
{{data}}
<br>
<button ng-click="buttonClick()">Clickme!</button>
</div>
The problem is:
Whenever the page is loaded, #/v1 is triggered.
If i click on 'Clickme', JUST AFTER THE PAGE LOADS, Error: Scopes.get(...) is undefined is fired.
But, if i navigate to #/v2 and then to #/v1, the scopes are getting stored and the error is NOT fired.
Is there is some problem with with routeProvider? All the controllers wont be loaded at on-load event?
Please help me on this.
Related
i want when user click on someone user ,show new view for that information.
I have two controlles,first get list of user,and it is work fine,but second controller have function which hava param of users id,but they show blank page.I realy don t know how to redrect view from second controller method.
This is my code:
<html>
<head>
<title>Angular JS Views</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular-route.js"></script>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "app">
<p>view Students</p>
<p>View Student</p>
<div ng-view></div>
<script type = "text/ng-template" id = "viewStudents.htm">
<ul ng-repeat="entry in pacijenti">
<li>{{ entry.ime }}</li>
<li>{{entry.prezime}}</li>
<li>{{entry.jmbg}}</li>
<button type="button" ng-click="getP(entry.jmbg)" >
</button>
<a ng-href='#viewStudent' ng-click="myCtrl.getP(entry.jmbg)" >click me</a>
</ul>
</script>
<script type = "text/ng-template" id = "viewStudent.htm">
<ul ng-repeat="entry2 in pac">
<li>{{entry2.dijagnoza}}</li>
<li>{{entry2.bolest}}</li>
link1
</ul>
</script>
</div>
<script>
var app = angular.module("app", ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'HomeController'
}).
when('/viewStudent', {
templateUrl: 'viewStudent.htm',
controller: 'myCtrl'
}).
otherwise({
redirectTo: '/viewsStudents'
});
}]);
app.factory('photos', ['$http', function($http) {
return $http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti")
.success(function(response) {
return response;
})
.error(function(response) {
return response;
});
}]);
app.controller('HomeController', ['$scope', 'photos', function($scope, photos) {
$scope.pacijenti=this;
photos.success(function(response) {
$scope.pacijenti =response;
});
}]);
app.controller('myCtrl', function($scope, $http) {
$scope.pac=this;
$scope.getP=function(jmbg){
$http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti/"+jmbg+"/pregledi")
.then(function(response) {
$scope.pac = response.data;
}, function(response) {
$scope.pac = "Something went wrong";
});
};
});
</script>
</body>
</html>
Modify your route to accept a jmbg id:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'HomeController'
}).
when('/viewStudent/:jmbg', {
templateUrl: 'viewStudent.htm',
controller: 'myCtrl'
}).
otherwise({
redirectTo: '/viewsStudents'
});
}]);
Then in the controller, retrieve the jmbg id:
app.controller('myCtrl', function($scope, $http, $routeParams) {
$scope.pac = this;
$scope.jmbg = $routeParams.jmbg;
$scope.getP = function(jmbg){
$http.get("http://localhost:8080/mavenproject2/fizijatar/12345/pacijenti/"+jmbg+"/pregledi")
.then(function(response) {
$scope.pac = response.data;
}, function(response) {
$scope.pac = "Something went wrong";
});
// Call the getP function with the jmbg id
$scope.getP($scope.jmbg);
};
});
The link to open the student view would look like this:
<a ng-href="#viewStudent/{{entry.jmbg}}">click me</a>
Here is a working plunker example: https://plnkr.co/edit/99aDJkuvIDopNoILNFGB?p=preview -- Please note, I removed the photo factory usage, and instead hard coded example data.
I'm using ngCordova "Network Information" plugin to get the online/offline status of the host device. I have followed this tutorial (which excellent, as are his other posts):
Josh Morony - Monitoring Online and Offline States in an Ionic Application
I have implemented the "ConnectivityMonitor" service as described in the article.
In one of my controllers/templates it works perfectly:
(function() {
'use strict';
angular
.module('myApp')
.controller('ResearchController', ResearchController);
ResearchController.$inject = ['$scope', '$stateParams', 'MyApi', 'ConnectivityMonitor'];
function ResearchController($scope, $stateParams, MyApi, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
...
}
<ion-view title="RESEARCH" ng-controller="ResearchController as vm" >
<ion-content>
<div>
ONLINE: {{vm.isOnline}}
</div>
</ion-content>
</ion-view>
Result:
ONLINE: true
However, in another controller/template this does not work and I have been at this for hours and hours:
(function() {
'use strict';
angular
.module('MyApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope','ConnectivityMonitor'];
function HomeController($scope, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
<ion-content class="background" ng-controller="HomeController as vm">
<p>ONLINE: {{vm.isOnline}}</p>
</ion-content>
Result:
ONLINE: {{vm.isOnline}}
Here ^^^ it seems that angular is not performing the databinding. I have all of my relevant controllers in index.html, as well as angularjs references.
Here is my implementation of the "ConnectivityMonitor" service:
(function() {
'use strict';
// http://www.joshmorony.com/monitoring-online-and-offline-states-in-an-ionic-application/
angular.module('MyApp').factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', connectivityMonitor]);
function connectivityMonitor($rootScope, $cordovaNetwork) {
return {
isOnline: function () {
if (ionic.Platform.isWebView()) {
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
isOffline: function () {
if (ionic.Platform.isWebView()) {
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
}
};
}
}
)();
Any idea why this would not be working? I'm new to AngularJS and Ionic so I'm thinking there is some nuance or convention that I'm overlooking. Thanks.
[ UPDATE 1 ]
I recreated this issue in an ionic starter app. There are two templates: Home.html and Workshere.html, with respective controllers. The online status is correctly displayed in the "Workshere" state, and is incorrect in the "Home" state. Also, adding the HomeController to Home.html (via ng-controller) seems to kill all interactivity on that page, can't even click the "Go to Workshere" link.
Home.html and home state is the default state for the MyApp. I'm starting to think that this is a timing issue an ConnectivityMonitor is not ready when the home state loads.
Code follows:
Home.html
<ion-view>
<ion-content ng-controller="HomeController">
<br/><br/><br/>
<p>HOME</p>
<p>ONLINE: {{vm}}</p>
<br/><br/>
<a ui-sref="workshere">Go to WorksHere</a>
</ion-content>
</ion-view>
home.controller.js
(function() {
'use strict';
angular
.module('myApp')
.controller('HomeController', HomeController);
HomeController.$inject = ['$scope','ConnectivityMonitor'];
function HomeController($scope, ConnectivityMonitor) {
$scope.vm = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
Workshere.html
<ion-view ng-controller="WorkshereController as vm" >
<ion-content>
<br/><br/><br/>
<p>WORKS HERE</p>
<p>ONLINE: {{vm.isOnline}}</p>
<br/><br/>
<a ui-sref="home">Go to Home</a>
</ion-content>
</ion-view>
workshere.controller.js
(function() {
'use strict';
angular
.module('myApp')
.controller('WorkshereController', WorkshereController);
WorkshereController.$inject = ['$scope', 'ConnectivityMonitor'];
function WorkshereController($scope, ConnectivityMonitor) {
var vm = this;
vm.isOnline = ConnectivityMonitor.isOnline();
activate();
////////////////
function activate() {
}
}
})();
app.js
angular.module('myApp', ['ionic', 'ngCordova'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'home.html'
})
.state('workshere', {
url: 'workshere',
templateUrl: 'workshere.html'
});
$urlRouterProvider.otherwise('/');
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/connectivityMonitor.js"></script>
<script src="js/home.controller.js"></script>
<script src="js/workshere.controller.js"></script>
</head>
<body ng-app="myApp">
<ion-nav-view>
</ion-nav-view>
</body>
</html>
ConnectivityMonitor.js
(function() {
'use strict';
// http://www.joshmorony.com/monitoring-online-and-offline-states-in-an-ionic-application/
angular.module('myApp').factory('ConnectivityMonitor', ['$rootScope', '$cordovaNetwork', connectivityMonitor]);
function connectivityMonitor($rootScope, $cordovaNetwork) {
return {
isOnline: function () {
if (ionic.Platform.isWebView()) {
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
isOffline: function () {
if (ionic.Platform.isWebView()) {
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
},
startWatching: function(){
if(ionic.Platform.isWebView()){
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
console.log("went online");
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
console.log("went offline");
});
}
else {
window.addEventListener("online", function(e) {
console.log("went online");
}, false);
window.addEventListener("offline", function(e) {
console.log("went offline");
}, false);
}
}
};
}
}
)();
Please see comments at the "UPDATE 1" marker.
Why don't you try it this way:
function HomeController($scope, ConnectivityMonitor) {
$scope.vm = ConnectivityMonitor.isOnline();
}
and for view
<ion-content class="background">
<p>ONLINE: {{vm}}</p>
</ion-content>
Here's the demo:
http://www.tanadsplinare.com.hr/tmp/ngtest/ngVer/
(enter 1, 2 or 3 in search field then click on any item.)
Now the item details display in the itemDetail div on the right side.
However, the ui-view is placed in child partial view, in the left panel under the list, it is itemsListDetailOutput div.
I don't know other way, so I quickly copy the innerHTML of the ui-view to the itemDetail (where I want to display the item detail, but I can't apply ui-view to it because there is already other ui-view there and the item list uses it) and clear the innerHTML of the ui-view. I guess I should do it on digest event, but I don't know how to do it, so I just used setTimeout:
$('#itemDetail').hide();
setTimeout(function() {
$("#itemDetail").html($("#itemsListDetailOutput").html()).fadeIn(200);
}, 10);
So basically:
1) is there other way to do it, the right way, instead of moving inner HTML to desired HTML element; and if there isn't:
2) how can I catch digest event to do it, instead of using setTimeout?
Thank you
EDIT:
I've posted it to plunker: http://plnkr.co/edit/EC4FBr9RtTvaycBteLJ3 , have no idea why it doesn't work there, but the code is there. I'll post it here also:
index.html:
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="css/app.css"/>
<script src="lib/jquery-2.0.1.min.js" type="text/javascript"></script>
<script src="lib/angular/angular.js" type="text/javascript"></script>
<script src="lib/angular/angular-ui-router.min.js" type="text/javascript"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/services.js" type="text/javascript"></script>
<script src="js/controllers.js" type="text/javascript"></script>
</head>
<body>
<nav id="menu">
Angular way
JS way
</nav>
<section>
<div id="contentWrapper">
<nav class="itemsListHolder" ng-controller="ItemsListHolderController">
<input ng-model="search" ng-change="searchUpdated(search)" type="search" id="search" placeholder="Search..." />
<div ui-view id="itemsList"></div>
enter 1, 2 or 3
</nav>
<div id="itemDetail" class="panel">Select the film from the list...</div>
</div>
</section>
<div id="preloader"></div>
</body>
</html>
/partials/ngItemsList.html:
<section ng-repeat="item in items">
<div class="itemsListItem" data-index="{{item.id}}" ng-click="displayDetail(item.id)">
<div class="dataTitleOriginal">{{item.titleOriginal}}</div>
<div class="dataTitleLocal">{{item.titleLocal}}</div>
<div class="dataYear">{{item.year}}</div>
</div>
</section>
<div ui-view id="itemsListDetailOutput"></div>
/partials/ngItemDetail.html:
<div class="itemDetailName">Original Title</div>
<div class="itemDetailValue titleOriginal">{{titleOriginal}}</div>
<div class="itemDetailName">Local Title</div>
<div class="itemDetailValue titleLocal">{{titleLocal}}</div>
<div class="itemDetailName">Year</div>
<div class="itemDetailValue year">{{year}}</div>
/js/app.js:
'use strict';
angular.module('myApp', [
'myApp.controllers',
'ui.router'
])
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('itemsList', {
url: '/list/:query',
templateUrl: 'partials/ngItemsList.html',
controller: 'ItemListController'
})
.state('itemsList.itemDetail', {
url: '/detail/:id',
templateUrl: 'partials/ngItemDetail.html',
controller: 'ItemDetailController'
})
;
//$locationProvider.html5Mode(true);
} ])
.run(['$rootScope', '$state', 'Main', 'Items', function($rootScope, $state, Main, Items) {
Main.init();
Items.initDatabase();
$rootScope.$on('$stateChangeStart', function() {
document.getElementById("preloader").style.display = "block";
setTimeout(function() {
document.getElementById("preloader").style.display = "none";
}, 5000);
});
$rootScope.$on('$stateChangeSuccess', function() {
document.getElementById("preloader").style.display = "none";
});
} ])
;
/js/services.js:
'use strict';
angular.module('myApp')
.factory('Main', function() {
return {
testdata: null,
init: function() {
}
}
})
.factory('Items', function(Main) {
var insertItem = function(permalink, titleOriginal, titleLocal, year) {
var items = getItemsList();
items.push({
permalink: permalink,
titleOriginal: titleOriginal,
titleLocal: titleLocal,
year: year
});
Main.testdata = items;
};
var initDatabase = function() {
// Fill Database.
if (!Main.testdata) {
insertItem("1111-film", "1111 orig", "1111", "1980");
insertItem("3333-film", "3333 orig", "3333", "1982");
}
};
var getItemsList = function() {
return (Main.testdata) ? Main.testdata : [];
};
var getItem = function(index) {
var list = getItemsList();
if (list && list.length && list.length > index) {
return list[index];
}
};
return {
initDatabase: initDatabase,
insertItem: insertItem,
getItemsList: getItemsList,
getItem: getItem
}
})
;
/js/controllers.js:
'use strict';
angular.module('myApp.controllers', [])
.controller('ItemsListHolderController', ['$scope', '$state', function($scope, $state) {
$scope.searchUpdated = function(query) {
$state.go('itemsList', {
query: query
});
};
} ])
.controller('ItemListController', ['$scope', '$state', '$stateParams', 'Items', function($scope, $state, $stateParams, Items) {
var query = $stateParams.query;
var result = Items.getItemsList();
var filteredResult = [];
for (var i = 0; i < result.length; i++) {
if (result[i].titleOriginal.indexOf(query) > -1 || result[i].titleLocal.indexOf(query) > -1 || result[i].year.indexOf(query) > -1) {
result[i].id = i;
filteredResult.push(result[i]);
}
}
$scope.items = filteredResult;
$scope.displayDetail = function(index) {
$state.go('itemsList.itemDetail', {
id: index
});
};
} ])
.controller('ItemDetailController', ['$scope', '$stateParams', 'Items', function($scope, $stateParams, Items) {
var itemId = $stateParams.id;
var item = Items.getItem(itemId);
$scope.titleOriginal = item.titleOriginal;
$scope.titleLocal = item.titleLocal;
$scope.year = item.year;
//xxxx UGLY FIX: display in ui-view, (it's set to display none anyway) and copy its innerHTML to another DOM element; also wait a while till digests
$('#itemDetail').hide();
setTimeout(function() {
$("#itemDetail").html($("#itemsListDetailOutput").html()).fadeIn(200);
}, 10);
} ])
;
UPDATE
Here is detailed Nested View Example please check to understand nested views in ui.router...
ANSWER
ui.router supports nested view which you can use in this situation.
As you set details page as child state of list so you can put a ui-view in your list html and tell details state to include itself into that ui-view
syntax for nested views is a bit different than the normal state defination. Instead of directly define your templateUrl and controller you should define them in views property.
so firstly change your state defination with this one
views: {
uiViewName#stateName: {
templateUrl: '...',
controller: '...'
}
}
so removing templateUrl and controller from your defination and put them into views property and you should set your stateName as well it is itemsList in your example...
Now you should add a ui-view with the name uiViewName (you can change it whatever you want) in your list html
...
<div ui-view="uiViewName"></div>
...
so whenever you go details page it will be injected that specific ui-view...
I have the the following files:
index.html
<html ng-app="gitHubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="app.js"></script>
<script src="MainController.js"></script>
<script src="gitHub.js"></script>
</head>
<body>
<h1>GitHub Viewer</h1>
<div ng-view>
</div>
</body>
</html>
main.html
<form name="searchUser" ng-submit="search(username)">
<input type="search" required="" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" />
</form>
app.js
(function(angular) {
'use strict';
angular.module('gitHubViewer', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({
redirectTo: "/main"
});
}
]);
})(window.angular);
MainController.js
(function(angular) {
'use strict';
angular.module('gitHubViewer', [])
.controller('MainController', ['$scope', '$interval', '$location',
function($scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = 'angular';
$scope.countdown = 5;
startCountdown();
}
]);
})(window.angular);
My problem is that the main.html file is not being loaded on ng-view when i have the routing on a separated file (app.js).
But if i remove the app.js file and add the .config on MainController.js,the main.html loads properly, here's the example:
(function(angular) {
'use strict';
angular.module('gitHubViewer', ['ngRoute'])
.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when("/main", {
templateUrl: "main.html",
controller: "MainController"
})
.otherwise({
redirectTo: "/main"
});
}
])
.controller('MainController', ['$scope', '$interval', '$location',
function($scope, $interval, $location) {
var decrementCountdown = function() {
$scope.countdown -= 1;
if ($scope.countdown < 1) {
$scope.search($scope.username);
}
};
var countdownInterval = null;
var startCountdown = function() {
countdownInterval = $interval(decrementCountdown, 1000, $scope.countdown);
};
$scope.search = function(username) {
if (countdownInterval) {
$interval.cancel(countdownInterval);
$scope.countdown = null;
}
};
$scope.username = 'angular';
$scope.countdown = 5;
startCountdown();
}
]);
})(window.angular);
Am i doing something wrong with the separated the files???
I think you are defining your module twice with the same name, instead add a handle to it and use that.
var app = angular.module('gitHubViewer', []);
app.controller(...
app.config(...
Here's your plunkr edited to work:
plunkr
You need to declare the module that is shared between scripts outside the IIFE, so that it is a global variable to be shared. See: IIFE and scope
That is app.js now has the module defined at the top:
var app = angular.module("gitHubViewer", ["ngRoute"]);
(function() {
and this line was removed from MainController.js:
var app = angular.module("gitHubViewer", ["$scope", "$interval", "$location"]);
Note: You also don't need to inject scope or services like $location, that are included in the base angularJs package, into the module. These should be injected directly into controllers.
Note: after the countdown the plunkr now breaks, because you need to add your UserController in.
When you create a new module you use the dependency array argument
angular.module('gitHubViewer', ['ngRoute']);
Then when you want to reference the existing module you leave out the second argument.
angular.module('gitHubViewer').run...
angular.module('gitHubViewer').controller....
AngulaR resolve API
The API says for resolve:
key – {string}: a name of a dependency to be injected into the controller.
#egghead, there is this video on the topic:
egghead - Angular resolve
What i do not understand is what that key object is for and why the author of the above video does inject the controller into itself
key – {string}: a name of a dependency to be injected into the
controller.
app.config(function($routeProvider) {
$routeProvider.
when('/', {
controller: 'ListCtrl',
resolve: {
myResolve: function(MyService) {
return MyService();
}
},
templateUrl:'./views/list.html'
})
});
Instead of (in the controller)
app.controller('MyController',function($scope,MyService){
$scope.data = MyService();
});
if you use resolve
app.controller('MyController',function($scope,myResolve){
$scope.data = myResolve;
});
UPDATE
a working example
<!doctype html>
<html ng-app="myModule">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="content" data-ng-view=""></div>
<script src="http://code.angularjs.org/1.0.8/angular.min.js"></script>
<script>
var myModule = angular.module('myModule', []);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: './index.html',
controller: 'IndexCtrl',
resolve: {
hello: function(Hello) {
return Hello.getMessages();
}
}
})
.otherwise({
redirectTo: '/'
});
});
myModule.factory('Hello', function($q, $timeout) {
var getMessages = function() {
var deferred = $q.defer();
$timeout(function() {
deferred.resolve('Hello');
}, 1000);
return deferred.promise;
};
return {
getMessages: getMessages
};
});
myModule.controller('IndexCtrl',function($scope,hello){
$scope.hello = hello;
});
</script>
</body>
</html>
the view
<p>{{hello}}</p>