Controller on angularJs - javascript

On the Link below on plunker, I am trying to do a simple page connecting view 1 to view 2.
On view 1 we can type a text which will be shown on View2.
My difficulty is trying to understand how I can connect the Controller1 mentioned in the $stateProviderState, to the
Controller1.js, to the view. I find it difficult to understand how the
factory works, how to do the injection.
Could anyone explain to me? Thank you.
Plnkr - Linking pages using ui-router
//app.module.js
var myApp = angular.module("myApp", ['ui.router']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html",
view: {
controller: 'Controller1'
}
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html",
view: {
controller: 'Controller2'
}
});
});
//Controller1.js
(function() {
'use strict';
angular
.module("myApp")
.factory('shareFactory', shareFactory)
.controller('Controller1', Controller1);
function Controller1(shareFactory, $scope, $http) {
var vm = this;
vm.textView1 = "SomethingToStartWith";
function getView1() {
shareFactory.getData()
.then(function(response) {
if (response.data) {
vm.textView1 = response.data;
console.log(vm.textView1);
} else {
console.log("Something was wrong");
return;
}
}, function(response) {
console.log("Entered this Error function");
});
}
}
});
//Index.html
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.5.5/angular.js" data-semver="1.5.5" data-require="angularjs#1.5.5"></script>
<script data-require="angular.js#<2" data-semver="1.5.7" src="https://code.angularjs.org/1.5.7/angular.js"></script>
<script data-require="ui-router#1.0.0-alpha.5" data-semver="1.0.0-alpha.5" src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-alpha.5/angular-ui-router.js"></script>
<script src="app.module.js"></script>
<script src="Controller1.js"></script>
<script src="share.factory.js"></script>
</head>
<body >
<div class="header" ng-style="{background:'red'}">header</div>
<div data-ui-view=""></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
</body>
</html>
//share.factory.js
(function() {
angular
.module("myApp")
.factory('shareFactory', shareFactory);
function shareFactory() {
var data = '';
return {
getData: function() {
return data;
},
setData: function(newData) {
data = newData;
}
};
}
})();

Maybe code explains itself?
Below code forked from your initial plunk can be found here http://plnkr.co/edit/WLe3TLTa6DKWUQ21lK3P
JavaScript
angular.module('myApp', ['ui.router'])
.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when('', 'view1');
// set up states
// no need to specify controllers in templates
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'view1.html',
controller: 'Controller1',
controllerAs: 'vm'
})
.state('view2', {
url: '/view2',
templateUrl: 'view2.html',
controller: 'Controller2',
controllerAs: 'vm'
});
})
// factory, shared data
.factory('shareFactory', function($q) {
var data = 'initial value';
// mock $http using $q which returns
// resolved/rejected promise, as would $http
return {
getData: function() {
return $q.when(data); // resolve
},
setData: function(val) {
if (val.length > 0) {
data = val;
return $q.when(); // resolve
} else {
return $q.reject('value can\'t be empty'); // reject
}
}
};
})
.controller('Controller1', function(shareFactory, $state) {
var vm = this;
// because async
shareFactory.getData()
.then(function(data) {
vm.data = data;
});
vm.set = function(data) {
shareFactory.setData(data)
.then(function() {
vm.error = null;
$state.go('view2');
})
.catch(function(e) {
vm.error = e;
});
};
})
.controller('Controller2', function(shareFactory) {
var vm = this;
shareFactory.getData()
.then(function(data) {
vm.data = data;
})
.catch(function(e) {
console.log(e);
});
});
index.html
<body >
<div data-ui-view></div>
</body>
view1.html
<div>
<h1>view1</h1>
<label>Enter a value: </label>
<input type="text"
ng-model="vm.data">
<input type="button"
class="btn btn-default"
value="Go to view2"
ng-click="vm.set(vm.data)">
<pre ng-bind="vm.error"></pre>
</div>
view2.html
<div>
<h1>view2</h1>
The value set in view1 is: <b ng-bind="vm.data"></b>
<input type="button"
class="btn btn-default"
value="Go to view1"
ui-sref="view1">
</div>

Check the plunker. Injecting factory to controller, controller to main module and ui-routing
Check this
html
<div class="header" ng-style="{background:'red'}">header</div>
<div ui-view></div>
<div class="footer" ng-style="{background:'blue'}">footer</div>
main Js
var myApp = angular.module("myApp", ['ui.router','ConrollerApp']);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/View1");
$stateProvider
.state("View1", {
url: "/View1",
templateUrl: "View1.html"
})
.state("View2", {
url: "/View2",
templateUrl: "View2.html"
});
});
Controller
var ctrl=angular.module("ConrollerApp",["Factory"])
ctrl.controller("AppController",function($scope,AppFactory){
$scope.data=AppFactory.useData();
})
Factory
var factoryapp=angular.module("Factory",[])
factoryapp.factory("AppFactory",function(){
return{
useData:function(){
var x=10;
return x;
}
}
})`

Related

How to Initialize third party JavaScript asynchronous library before loading AngularJS

I'm facing problem while initializing a third party JavaScript API (iHUB) inside RUN method of AngularJS. Currently the code is behaving in asynchronous mode. I want IHUB to first initialize and then AngularJS route/controller should get called. (Is it possible to make utilization of the callback method provided by IHUB ?)
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.run(['$window', 'myService', function($window, myService) {
//initialize IHUB
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
alert('started!!');
}
}]);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl'
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl'
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
There is only one way to achieve a "real" before AngularJS initialization behavior by using angular.bootstrap();. This allows you to initialize your AngularJS application manually.
Note: You should not use the ng-app directive when manually bootstrapping your app.
> Fiddle demo
View
<div ng-controller="MyController">
Hello, {{greetMe}}!
</div>
Application
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.greetMe = 'World';
}]);
var actuateDummy = {
initialize: function (callback) {
setTimeout(callback, 2500);
}
};
actuateDummy.initialize(function () {
angular.element(function() {
angular.bootstrap(document, ['myApp']);
});
})
This is an other approach which uses the resolve state of ui-router. This service only initializes iHUB if it not has been initialized yet:
This service also returns the actuate object. In that way you can use it in your controller or components after init.
> Demo fiddle
View
<nav>
<a ui-sref="state1">State 1</a>
<a ui-sref="state2">State 2</a>
</nav>
<div ui-view></div>
AngularJS Application
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function($stateProvider, $urlRouterProvider) {
$stateProvider.state("state1", {
url: "#",
template: "<p>State 1</p>",
controller: "Ctrl1",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
}).state("state2", {
url: "#",
template: "<p>State 2</p>",
controller: "Ctrl2",
resolve: {
iHubInit: function(iHubService) {
return iHubService.init()
}
}
});
});
myApp.controller("Ctrl1", function($scope, iHubService) {
console.log("Ctrl1 loaded.");
});
myApp.controller("Ctrl2", function($scope, iHubService) {
console.log("Ctrl2 loaded.");
});
myApp.service('iHubService', ["$q", function($q) {
this.iHubServiceInitialized = false;
this.actuate = null;
this.init = function() {
if (!this.iHubServiceInitialized) {
//Init
var self = this;
var deferred = $q.defer();
this.actuate = new actuate();
//initialize
this.actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", function() {
self.iHubServiceInitialized = true;
deferred.resolve(self.actuate);
});
return deferred.promise;
} else {
return this.actuate;
}
}
}]);
Try to add a resolve attribute when configuring your route provider like below:
var nameApp = angular.module('nameApp', ['ngRoute']);
nameApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/:tabname', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'tabDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
when('/:tabname/:reportName', {
templateUrl: 'pages/analyticsDetail.html',
controller: 'reportDetailCtrl',
resolve: {
ihubInit: ['iHubService', function (iHubService) {
return iHubService.init();
}]
}
}).
otherwise({
redirectTo: '/Buy Side Dashboard'
});
}]);
nameApp.service('iHubService', ["$q", function($q){
this.init = function() {
var deferred = $q.defer();
var actuate= new actuate();
actuate.initialize('http://localhost:8700/iportal', settings.reqOps, "user", "pwd", callback);
function callback(){
deferred.resolve();
}
return deferred.promise;
}
}]);

Angularjs button click with ui router is not working

Hi I am developing angular js application. I am using ui-routing technique. I am facing issues in button click event. Below is my main.js file.
var app = angular.module('RoslpApp', ['pascalprecht.translate', 'ui.router']);
app.config(function ($stateProvider, $urlRouterProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
$stateProvider.state('ForgotPassword', {
url: '/ForgotPassword',
templateUrl: 'ForgotPassword/ForgotPassword.html',
controller: 'ForgotPassword'
});
$stateProvider
.state('ForgotPassword.ResetPassword', {
url: '/ResetPassword',
templateUrl: 'ForgotPassword/ResetPassword.html',
controller: 'ResetPassword'
});
});
});
Below is my forgotpassword.html
<div class="container">
<div ui-view></div>
</div>
Here i am injecting ResetPassword.html.
Below is my ResetPassword.html
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
Above button does not work.
This is my Resetpasswordcontroller.
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();
Resetpasswordservice.js
app.service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
$scope.ResetPassword is not working and i am not getting error also. Any help would be appreciated. Thank you.
I think your arguments are wrong, try to change it to something like this (corresponding arguments):
[
'$rootScope',
'ResetPasswordService',
'$scope',
'$translatePartialLoader',
'$translate',
function ($rootScope, $ResetPasswordService, $scope, $translatePartialLoader, $translate){
[...]
}
]
Your dependency injection order is wrong. Try this one:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$scope', '$http', '$translatePartialLoader', '$translate', 'ResetPasswordService', function ($scope, $http, $translatePartialLoader, $translate, ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
$http.post('/api/projects/7').then(function (response) {
alert(JSON.stringify(response.data));
}, function (error) {
console.log(error);
});
}
}]);
})();
ResetPasswordService.js
angular.module('RoslpApp').service("ResetPasswordService", function ($http, $state) {
alert("aaa");
this.ResetPassword = function () {
var url = '/api/projects/7';
return $http.post(url).then(function (response) {
return response.data;
});
}
});
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
var myApp = angular.module("myApp", []);
myApp.controller("myController", ['$rootScope' , function( $scope){
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
<!-- begin snippet: js hide: false console: true babel: false -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller= "myController">
<div class="button-container">
<input type="submit" value="Submit" id="input-submit" data-ng-click="ResetPassword()">
</div>
</div>
</body>
There may be problme while passing the dependency to controller in passing the arguments to callback.I tried simple way with one arguments.its work to me.Check it
Change your code like below. Your order and reference is wrong.
angular.module('RoslpApp').controller('ResetPassword', ['$rootScope','$scope', '$translatePartialLoader', '$translate','ResetPasswordService', function ($rootScope, $scope, $translatePartialLoader, $translate,ResetPasswordService) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
Change you ResetPassword.html code as following:
<div class="button-container">
<input type="button" value="Submit" id="input-submit" ng-click="ResetPassword()" />
</div>
Also, edit you controller as the problem is due to incorrect dependencies order. You should rewrite as:
(function () {
angular.module('RoslpApp').controller('ResetPassword', ['$ResetPasswordService','$scope', '$translatePartialLoader', '$translate', function ($ResetPasswordService, $scope, $translatePartialLoader, $translate) {
alert("Works");
$scope.ResetPassword = function () {
var sub = {
mobilenumber: $scope.updateID,
dob: $scope.updateName
};
alert("does not works");
var servCall = ResetPasswordService.ResetPassword(sub);
servCall.then(function (data) {
}, function (data) {
alert(JSON.stringify(data.data));
});
}
}]);
})();

Angularjs: Uncaught ReferenceError $rootScope is not defined

I am trying to run and got this message:
Uncaught ReferenceError: $rootScope is not defined at app.js line 12
here is my js/app.js
angular.module('addEvent', ['ngRoute'])
.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when('/add-event', {
templateUrl: 'views/add-event.html',
controller: 'formCtrl',
controllerAs: 'eventCtl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}])
.run(['$rootScope', function() {
$rootScope.event = [];
}]);
this js/controller.js
angular.module('addEvent')
.controller('formCtrl', ['eventFactory', function(eventFactory) {
//$scope.event=[];
this.event = eventFactory.getAllEvents();
this.submitForm = function(form) {
eventFactory.createEvent(angular.copy(form), this.event);
// $scope.event.push(angular.copy(form));
console.log($scope.event);
}
}])
services/eventFactory.js
angular.module('addEvent')
.factory('eventFactory', function() {
var eventFactory = {};
var events = [];
eventFactory.getAllEvents = function() {
return events;
}
eventFactory.createEvent = function(event, eventList) {
events.push(event);
eventList = events;
return eventList;
}
return eventFactory;
})
And at index.html I added script this way
<script src="./js/jquery-1.12.4.js"></script>
<script src="./js/bootstrap.js"></script>
<script src="./js/angular.min.js"></script>
<script src="./js/angular-route.js"></script>
<script src="./js/app.js"></script>
<script src="./js/controller.js"></script>
<script src="./services/eventFactory.js"></script>
You need to inject $rootScope in the run() method
.run(['$rootScope',function($rootScope){
$rootScope.event=[];
}]);
instead of
.run(['$rootScope',function(){
$rootScope.event=[];
}]);
You forgot to include the $rootScope service in the run function as a parameter that's why you see the error Uncaught ReferenceError: $rootScope is not defined
angular
.module('demo', [])
.run(run)
.controller('DefaultController', DefaultController);
run.$inject = ['$rootScope'];
function run($rootScope) {
$rootScope.events = [];
console.log($rootScope.events);
}
function DefaultController() {
var vm = this;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
</div>
</div>

How to manage factory single request data in a state with some ui views

Being pretty new at AngularJS, I'm trying to understand how to manage a single JSON that is comming from a single $http.get request which is gonna be used by 2 different controllers in 2 diferent ui-view.
The idea is to show the data of the user in the first ui-view and the data of the story in the second one.
Right now my factory do 2 $http requests, due to it's called twice by the two controllers.
Right now what I have is what it follows:
homeFactory.js
var homeFactory = angular.module('home.factory', []);
homeFactory.factory('homeData', [ '$http', '$q', function ($http, $q) {
var endpoints = null;
return {
getStories: function(url) {
return endpoints ?
$q(function(resolve, reject) { resolve(endpoints); }) :
$http.get(url + '/main/get', {
transformRequest : angular.identity,
headers : {'Content-Type' : undefined}
}).then(function(data) { endpoints = data; return data; });
}
};
}]);
home.js
var home = angular.module('home', ['home.factory']);
home.controller('topbarCtrl', [ 'CONFIG', 'homeData', function(CONFIG, homeData) {
var data = this;
data.stories = {};
homeData.getStories(CONFIG.API_URL).then(function(response) {
data.stories = response.data.stories;
}, function(error) {
console.log("Failed to load end-points list");
});
}]);
home.controller('contentCtrl', [ 'CONFIG', 'homeData', function(CONFIG, homeData) {
var data = this;
data.stories = {};
homeData.getStories(CONFIG.API_URL).then(function(response) {
data.stories = response.data.stories;
}, function(error) {
console.log("Failed to load end-points list");
});
}]);
app.js
(function () {
var app = angular.module('init', [
'home', 'ui.router'
]);
app.run([
'$rootScope',
'$state',
'$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
app.constant('CONFIG', {
'API_URL': 'https://xxxxxxxxx/',
'S3_PATH': 'http://resources.xxxxxxxxx.com',
'CLOUDFRONT': 'http://resources.xxxxxxxxx.com'
});
app.config([
'$stateProvider',
'$urlRouterProvider',
'$locationProvider',
'$sceDelegateProvider',
function ($stateProvider, $urlRouterProvider, $locationProvider, $sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://resources.xxxxxxxxx.com/**'
]);
$urlRouterProvider
.when('/logout', '/')
.otherwise('login');
$stateProvider
.state('home', {
url: "/home",
views: {
'header': { templateUrl: "app/Home/_topbar.html" },
'content': { templateUrl: "app/Home/_home.html" },
'footer': { templateUrl: "app/Home/_navbar.html" }
}
});
}
]);
}());
index.html
<!DOCTYPE html>
<html lang="en" ng-app='init'>
<head>
<meta charset="utf-8">
<script src="js/angular.min.js"></script>
<script src="js/angular-ui-router.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js"></script>
<script src="app/app.js"></script>
</head>
<body>
<script src="app/Home/home.js"></script>
<script src="app/Home/HomeFactory.js"></script>
<div ui-view="main">
<div ui-view="header"></div>
<div class="wrapper" ui-view="content"></div>
<nav ui-view="footer"></nav>
</div>
<script src="js/sha512.js"></script>
</body>
</html>
How could I achieve what I need?
Thanks in advice.
UPDATE
The solution I applied is on the main controller is to request the data via resolve directive and asign a controller to each view as it follows:
$stateProvider
.state('home', {
url: "/home",
resolve: {
response: [ 'CONFIG', '$http', function(CONFIG, $http) {
return $http.get(CONFIG.API_URL + '/home').then(function(response) {
return response.data;
});
}]
},
views: {
'header': { templateUrl: "app/Home/_topbar.html", controller: 'headerCtrl', controllerAs: 'my' },
'content': { templateUrl: "app/Home/_home.html", controller: 'contentCtrl', controllerAs: 'my' },
'footer': { templateUrl: "app/Home/_navbar.html", controller: 'footerCtrl', controllerAs: 'my' }
}
});
Then you don't need to declare ng-controller to the html view.
You can use ui-router's resolve to make the api call and inject the resolved data into the controller.
app.js
$stateProvider
.state('home', {
url: "/home",
resolve: {
response: ['homeData', '$q', 'CONFIG', function(homeData, $q, CONFIG) {
var deferredData = $q.defer();
homeData.getStories(CONFIG.API_URL).then(function(response) {
return deferredData.resolve({
data: response.data
});
})
return deferredData.promise;
}]
}
views: {
'header': { templateUrl: "app/Home/_topbar.html" },
'content': { templateUrl: "app/Home/_home.html" },
'footer': { templateUrl: "app/Home/_navbar.html" }
}
});
Controller:
home.controller('topbarCtrl', ['response', function(response) {
console.log(response.data) //this will contain the response data
}]);
home.controller('contentCtrl', ['response', function(response) {
console.log(response.data) //this will contain the response data
}]);

angularjs: getting route resolved data outside template

On loading '/', I am getting 'content' and 'sidebar'using 'myService' and resolve option in route provider and I can render the 'content' to the template ($scope.contents = content;).
But $scope.sideBar = sideBar; is not working. This is because sideBar is outside the template ?
How can I render sidebar items on loading '/' ? Is it possible to pass this data (sidebar) to the indexCtrl?
app.js
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'contents.html',
controller: 'Myctrl',
resolve: {
content: function(myService){
return myService.getContent();
},
sideBar: function(myService){
return myService.getSideBar();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('Myctrl', function (content, sideBar, $scope) {
$scope.contents = content;
$scope.sideBar = sideBar;
});
myApp.controller('indexCtrl', function($scope) {
});
myApp.service("myService", function () {
this.getContent = function () {
return 'Main contents';
}
this.getSideBar = function () {
return 'side bar'
}
});
index.html
<div ng-app="MyApp" ng-controller="indexCtrl">
<div class="sidebar">
{{sideBar}}
</div>
</div>
<div class="main">
<div ng-view></div>
</div>
</div>
contents.html
<div>{{contents}}</div>
You can inject your myService into your indexCtrl and access the function getSideBar like this
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar();
});
this will get the string from your getSideBar function when your indexCtrl is first initialized. If you do this:
myApp.controller('indexCtrl', function($scope, myService) {
$scope.sideBar = myService.getSideBar;
});
and inside index.html:
<div class="sidebar">
{{sideBar()}}
</div>
The string will update when the data in your service updates.

Categories