I Need to use same data on Two different Controller, One is page while other is Modal Popup. I created service which will perform $http.get to pull data. However, when I apply service to Modal Popup, it stops loading and even data is not load anywhere.
My Service
(function(){
'use strict';
angular.module('sspUiApp.services')
.service('AdUnitService', ['$http', '$rootScope', 'API_URL', function($http, $scope, API_URL) {
var data = $http.get('data/selectAdUnits.json');
return {
getAdFormats: function() {
console.log("inside function");
return data;
},
setAdFormats: function(value) {
}
}
}]);
})();
My Both Controller with Services added.
(function(){
'use strict';
angular.module('sspUiApp.controllers')
.controller('AdUnitFormatCtrl', ['$scope', '$state', 'AdUnitService', function ($scope, $state, AdUnitService) {
$scope.details = AdUnitService.getAdFormats();
}])
.controller('ModalDemoCtrl', ['AdUnitService', function ($scope, $uibModal, AdUnitService) {
$scope.open = function (size) {
// $scope.details = AdUnitService.getAdFormats();
$scope.$modalInstance = $uibModal.open({
scope: $scope,
templateUrl: 'views/select_ad_format.html',
size: size,
});
};
$scope.cancel = function () {
$scope.$modalInstance.dismiss('cancel');
};
$scope.details = AdUnitService.getAdFormats();
alert($scope.details);
}])
})();
And HTML
<div id="selectAdFormats" ng-controller="ModalDemoCtrl">
<div class="container">
<div class="ad-format-section">
<div class="row">
<div class="col-lg-3 col-md-3 col-sm-2 col-xs-6 selectedAdFormatData" ng-repeat="frmt in details.adformat">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
<img ng-src="../images/{{ frmt.ad_image }}" ng-if="frmt.ad_image"/>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
<span class="formatName">{{ frmt.name }}</span>
</div>
</div>
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
<span class="resSize">{{ frmt.size }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
angular.module('sspUiApp.services')
angular.module('sspUiApp.controllers')
Your service is in a different module, that's why you can't get to it, if you declare it into the same module it should work
Option 2:
Include your second module sspUiApp.services in your decleration of sspUiApp.controllers
for more info: Angular js seperation to different modules in different js files
Update:
var data = $http.get('data/selectAdUnits.json');
return {
getAdFormats: function() {
console.log("inside function");
return data;
},
setAdFormats: function(value) {}
}
The problem is is that data is asynchronious and you don't treat it like so:
$scope.details = AdUnitService.getAdFormats();
alert($scope.details);
You try to alert a promise, instead of waiting for it to resolve and alerting the result, if you change it into the following it should work:
AdUnitService.getAdFormats().then(function(details) {
alert(details);
});
This way angular will wait on the result before executing the code.
More info about Angular promises here: https://docs.angularjs.org/api/ng/service/$q
Related
I have been facing this from a long time, it is thrown when I'm trying to bind data to a variable in the html using {{}}. I used ngRoute for routing among different pages. The above mentioned error occurs when I'm trying to bind data to a variable or ng-model in the HTML.
But it works fine when the model's value is already declared in the controller.
The data that I'm receiving is from a custom service, which eventually makes an http GET request upon calling it from a controller.
<html ng-app="bgpsApp">
<body>
<div ng-view></div>
</body>
<!-- scripts loaded in a sequence:
jquery, angular.js(1.6.9), angular-route.js, app.js, customservices.js -->
</html>
app.js
var bgpsapp = angular.module('bgpsApp', ['ngRoute']);
bgpsapp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'brahmagpslogin.html'
})
.when('/portal', {
resolve: {
"check": function($location, $rootScope) {
if (!$rootScope.logStatus) {
$location.path('/');
}
}
},
templateUrl: 'portal.html'
})
.otherwise({
redirectTo: '/'
})
})
bgpsapp.controller('MainController', ['$scope', '$rootScope', '$http', 'services', function($scope, $rootScope, $http, services) {
services.getDashboardData($rootScope.master.userId).then(function(response) {
$scope.vehiclesStatus = response.data.data.vehiclesStatus;
console.log($scope.vehiclesStatus);
// ** assigning value to bind **
$scope.vehicleCount = $scope.vehiclesStatus.vehicleCount;
}, function(response) {
alert(response.data.message);
});
}]);
portal.html
<div id="wrapper" ng-controller="MainController">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-7 col-lg-7">
<h4>Vehicles
<small> Status</small>
</h4>
</div>
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-5">
<h4>
<!-- trying to bind data to this variable -->
{{vehicleCount}}
<small>Trucks</small>
</h4>
</div>
</div>
</div>
custom service js
bgpsapp.service('services', function($http) {
this.baseURL = "http://xxx/api/data";
this.getDashboardData = function(customerId) {
var d_response = {};
var response = $http.get(this.baseURL + "/customer/data/dashboard?userId=" + customerId);
return response;
}
});
I have the following code which displays a static JSON object in a grid.
var app = angular.module('app', ['ui.bootstrap']);
app.controller('ModalInstanceCtrl', function($scope, $modalInstance, customer) {
$scope.customer = customer;
});
app.controller('CustomerController', function($scope, $timeout, $modal, $log) {
$scope.customers = [{
name: 'Movie Title 1',
details: 'http://image.tmdb.org/t/p/w342//lFSSLTlFozwpaGlO31OoUeirBgQ.jpg',
}, {
name: 'Movie Title 2',
details: 'http://image.tmdb.org/t/p/w342//tgfRDJs5PFW20Aoh1orEzuxW8cN.jpg',
}, {
name: 'Movie Title 3',
details: 'http://image.tmdb.org/t/p/w342//wJXku1YhMKeuzYNEHux7XtaYPsE.jpg',
}];
// MODAL WINDOW
$scope.open = function(_customer) {
var modalInstance = $modal.open({
controller: "ModalInstanceCtrl",
templateUrl: 'myModalContent.html',
resolve: {
customer: function() {
return _customer;
}
}
});
};
});
I need to be able to use this RESTful API source:
$http.get("http://api.themoviedb.org/3/movie/now_playing?api_key=ebea8cfca72fdff8d2624ad7bbf78e4c")
.success(function(response) {
console.log(response);
$scope.results = response.results;
});
and enable the click event to trigger the modal as it does now, except it needs to grab the details of each of the items in the JSON object and display in the modal.
The ng-repeat:
<div class="container">
<div class="row">
<div ng-repeat="items in results">
<img class="col-lg-3 col-md-3 col-sm-3 col-xs-12 thumbnail" ng-src="http://image.tmdb.org/t/p/w342/{{items.poster_path}}">
</div>
</div>
</div>
Using this fiddle: http://jsfiddle.net/8s9ss/224/ as a base, I need to have the buttons replaced by the images coming through the REST API and they should trigger a modal on click.
This should be all you need
<div ng-repeat="items in results">
<a ng-click="open(items)" class="col-lg-3 col-md-3 col-sm-3 col-xs-12 thumbnail">
<img ng-if="items.poster_path" ng-src="http://image.tmdb.org/t/p/w342/{{items.poster_path}}">
<div class="caption" ng-hide="items.poster_path">
<h3>{{items.title}}</h3>
</div>
</a>
</div>
You'll need to tweak your modal template to show the different properties but you should be able to figure it out.
http://jsfiddle.net/8s9ss/229/
I am unable to get an angular tab other than the first one to be active on load. I am passing a url parameter such as ?location=Tucson to make that decision. I would like the second tab to display as active on load. Oddly enough the first tab is being set to active automatically, perhaps this is by default.
I am using
* angular-strap
* #version v2.1.4 - 2014-11-26
How can I set the second tab to active through the controller?
This is my setup
<section class="mainbar" data-ng-controller="contactus as vm">
<div>
<tabset>
<tab class="tab-pane" id="Tampa" heading="Tampa">
<tab-heading>Tampa</tab-heading>
<div class="actionBtn">
<a id="tpabtn" class="btn btn-default ldbtn request" data-ng-click="vm.getcontactformF()">
<div><span class="glyphicon glyphicon-envelope"></span></div>
<div>
<div class="title">Have Questions?</div>
<div>Send us a message</div>
</div>
</a>
</div>
</tab>
<tab class="tab-pane" id="Tucson" active="active">
<tab-heading>Tucson</tab-heading>
<div class="actionBtn">
<a href="tel:8885210206" class="btn btn-default ldbtn">
<div><span class="glyphicon glyphicon-earphone"></span></div>
<div>
<div class="title">RV Service</div>
<div class="phone">888.521.0206</div>
</div>
</a>
</div>
</tab>
</tabset>
</div>
<script type="text/ng-template" id="_contactfservice.html">
<div data-ng-include data-src="'/app/form/contactusform.html'"></div>
</script>
</section>
JS
(function () {
'use strict';
var controllerId = "contactus";
angular
.module('app')
.controller(controllerId, ['$location', '$window', '$rootScope', '$scope', '$sce', '$q', 'common', 'config', 'bootstrap.dialog', 'datacontext', contactus]);
function contactus($location, $window, $rootScope, $scope, $sce, $q, common, config, bsDialog, datacontext) {
/* jshint validthis:true */
var vm = this;
vm.highlightLocation = highlightLocation;
activate();
function activate() {
common.activateController([getLocationHours()], controllerId).then(function () {
common.postLoad();
log('Activated contact us View test test');
$window.ga('send', 'event', $location.path(), 'form-viewed');
highlightLocation();
});
}
function highlightLocation() {
var location = common.getQueryStringParameter('location', document.location.href);
console.log(location);
if (location == "Tucson") {
$scope.tabs = [{active: false}, {active: true}];
}
}
}
})();
some weird issue with bootstrap ui, this works.
$scope.data = {};
$timeout(function () {
$scope.vm.data.static2 = true;
}, 0)
I have some controllers and would like to share some datas from each others.
so I built a factory to pass those data ("anagType") from "AnagTypeController" to "CourseCatController", but the second controllers is parsed before the first one.
This is the HTML:
<div id="workArea" class="row">
<div class="col-md-6">
<div class="panel panel-info" ng-controller="Controller1">
...
</div>
</div>
<div class="col-md-6">
<div class="panel panel-warning" ng-controller="AnagTypeController">
...
</div>
<div class="panel panel-warning" ng-controller="Controller3">
...
</div>
</div>
<div class="clearfix"></div>
<div class="col-md-4">
<div class="panel panel-danger" ng-controller="CourseCatController">
...
</div>
</div>
<div class="col-md-4">
...
</div>
<div class="col-.md-4">
...
</div>
<div class="clearfix"></div>
</div> <!-- /#workArea-->
... and this is the angularjs:
app.controller('AnagTypeController', ['$scope', '$http', 'MsgBox', 'EmployeeMng',
function($scope, $http, MsgBox, EmployeeMng) {
$scope.anagType = [];
$scope.getList = function() {
$http({
method: "GET",
url: "../../xxx"
})
.success(function(data) {
$scope.anagType = data;
EmployeeMng.addAnagType($scope.anagType);
})
.error(function(data, status) {
console.log('ERROR AnagTypeController getList ' + data + ' ' + status);
});
};
$scope.getList();
}
]);
app.controller('CourseCatController', ['$scope', '$http', 'MsgBox', 'EmployeeMng',
function($scope, $http, MsgBox, EmployeeMng) {
$scope.anagType = [];
$scope.courseCats = [];
$scope.courseCatsObbl = [];
$scope.getCourseCats = function() {
$scope.anagType = EmployeeMng.anagType;
...
}
$scope.getCourseCats();
}
]);
Perhaps am I using angular in the wrong way?
Rather than making the call in one controller to set the data, you should move that code to the actual service itself.
All your controllers that need the data can then call the service to get the data.
So I have the following two controllers, a parent and a child, and I need a value that is dynamically added to the parent scope passed on into the child scope. I really can't understand how the service injection works either. Here is my parent controller:
'use strict';
angular.module("myApp").controller("singleTopicController", ["RestFullResponse", "Restangular", "localStorageService", "$scope", "$window", "$stateParams", function(RestFullResponse, Restangular, localStorageService, $scope, $window, $stateParams){
var topics = Restangular.one('topics', $stateParams.id);
var Topics = topics.get({},{"Authorization" : localStorageService.get('***')}).then(function(topic){
$scope.topic = topic;
$scope.topic.id = topic.id;
$window.document.title = 'Example | ' + $scope.topic.topic_title;
console.log($scope.topic);
});
}]);
And my child controller which needs the topic.id to work.
'use strict';
angular.module("myApp").controller("commentSingleController", ["RestFullResponse", "Restangular", "localStorageService", "$scope", "$state", "$stateParams", "$timeout", function(RestFullResponse, Restangular, localStorageService, $scope, $state, $stateParams, $timeout){
$scope.topic = {};
var oneTopic = Restangular.one('topics', $scope.topic.id);
oneTopic.get({}, {"Authorization" : localStorageService.get('***')}).then(function(topic) {
topic.getList('comments', {}, {"Authorization" : localStorageService.get('***')}).then(function(comments){
$scope.comments = comments;
console.log($scope.comments);
});
});
$scope.isCollapsed = true;
var comments = Restangular.all('comments');
$scope.commentData = {
//topic_id: $scope.parent.topic.id
};
$scope.postComment = function(mood) {
$scope.commentData.mood = mood;
comments.post($scope.commentData, {}, {"Authorization" : localStorageService.get('***')}).then(function(response){
$state.transitionTo($state.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
}, function(response){
$scope.error = response.data.message;
})
};
}]);
If I add
console.dir($scope.$parent);
to the child controller, topic is obviously there.
But if I try
console.dir($scope.$parent.topic);
I get undefined.
I tried wrapping the Restangular.get() of the child controller in a watcher but that didn't do anything.
$scope.$watch('topic', function{
Restangular.one() ...})
Where am I going wrong here.
<div class="main-left-column">
**<div ng-controller="singleTopicController">** //my main controller
<div class="topic-full">
<div class="topic-left">
<div class="topic-left-inner">
<a ui-sref="main.topic({id: topic.id})"><h4>{{ topic.topic_title }}</h4></a>
<hr>
<img ng-src="{{ topic.image_url }}" class="img-responsive img-topic" tooltip="{{ topic.topic_title}}"/>
<hr ng-if="topic.image_url">
<p>{{ topic.topic_content }}</p>
</div>
</div>
<div class="topic-right">
**<div class="topic-right-inner" ng-controller="commentSingleController">** //child controller
<img ng-src="{{ topic.profile_pic }}" width="60px" class="profile-pic"/>
<div class="topic-data">
<h4 class="topic-data">{{ topic.author_name }}</h4>
<h5 class="topic-data">- posted on {{ topic.created_at }}</h5>
</div>
<div class="comment-count">
<div class="comment-count-mood red" tooltip="Negative comments"><p>{{ topic.comments_angry }}</p></div>
<div class="comment-count-mood yellow" tooltip="Neutral comments"><p>{{ topic.comments_sad }}</p></div>
<div class="comment-count-mood green" tooltip="Positive comments"><p>{{ topic.comments_happy }}</p></div>
</div>
<div class="clear"></div>
<hr>
<p ng-if="comments.length == 0">No comments</p>
<div class="line-through">
<div ng-repeat="comment in comments">
<div class="comment-left">
<img ng-src="{{ comment.profile_pic }}" width="40px" class="comment-pic"/>
<div class="comment-mood" ng-class="{'red': comment.mood == 2, 'yellow': comment.mood == 1, 'green': comment.mood == 0}"></div>
</div>
<div class="comment-right">
<h4 class="comment-data">{{ comment.author_name }}</h4>
<p>{{ comment.comment }}</p>
</div>
<div class="clear"></div>
<hr class="dotted" ng-if="!$last">
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
UPDATE: Added HTML. Controller wrappers are in asterisks.
Your topic won't be created until your .get in your parent controller resolves, which is probably after the initialisation of the child controller.
If you remove the $scope.topic = {} from the child controller and add a $watch for topic.id you should be able to use the id in there.
Really you shouldn't need $scope.$parent as $scope should have everything the parent does unless it's been hidden by something in the child scope or there's an isolate scope in the way (there isn't in this case).