I tried to change value on my DOM. but it doesn't work well.
This is my source
<div class="header_player_info" ng-controller="playerCtrl">
<div>{{ playbackTimeCurrent }} / {{ playbackTimeTotal }}</div>
{{playerInfo.song}}
</div>
<div class="ut_player" ng-controller="playerCtrl">
<div>
<span>{{ playbackTimeCurrent }} / {{ playbackTimeTotal }}</span>
<div> {{playerInfo.song}}</div>
<div>{{playerInfo.artist}}</div>
</div>
</div>
When called $scope.updatePlayerInfo PlayerCtrl's $scope will be change,
but only second DOM ng-controller="playerCtrl" apply $scope data. First ng-controller="playerCtrl" does not bind scope data.
any problem with my logic?
app.controller('playerCtrl', ['$scope', '$http', '$location', 'playList', function ($scope, $http, $location, playList) {
$scope.playerInfo = { // init playerInfo
cover: 0,
song: "Please select song."
}
//Other $scope Function call updatePlayerInfo.
$scope.updatePlayerInfo = function(songData) {
$scope.playerInfo = {
cover: songData.cover,
key: songData.key,
song : songData.song_en,
artist: songData.artist_en
};
$scope.playerPaused = false;
};
}]);
Related
I have the parent view defined as:
<div ng-app="myProSupMod" ng-controller="DefaultController" class="container">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<img src="~/Content/Images/logo.jpg" />
<b class="projectTitle">Production Support Tool</b>
</div>
</div>
<div ng-show="DefaultProps.UserDivVisible" class="page-header"
style="font-weight:bold;height:30px;border-bottom:1px solid #d1d1d4;width:100%">
<div style="float:right;"><span style="margin-right:10px;">
Welcome
<a class="text-success" href="#">
{{DefaultProps.LoggedInUsername }}
</a></span>|
<a href="#" style="margin-left:5px;" class="text-danger"
ng-click="LogUserOut()">Logout
</a>
</div>
</div>
</div>
<ng-view></ng-view>
</div>
Its controller:
myProSupMod.controller("DefaultController", ['$scope', '$rootScope',
'$location', '$route', function ($scope, $rootScope, $location, $route) {
if (!sessionStorage.getItem("LoggedInUsername")) {
$scope.DefaultProps = {
LoggedInUsername: "",
UserDivVisible: false
};
$location.path('/');
}
else {
$scope.DefaultProps = {
LoggedInUsername: sessionStorage.getItem("LoggedInUsername"),
UserDivVisible: true
};
}
$scope.LogUserOut = function () {
sessionStorage.setItem("UserDivVisible", false)
$location.path('/')
}
}])
And one of my child child controller is like
myProSupMod.controller("LoginController", ['$scope', '$rootScope',
'$uibModal', 'LoginService', '$location', function ($scope, $rootScope,
$uibModal, LoginService, $location) {
$scope.DefaultProps.LoggedInUsername = ""
$scope.DefaultProps.UserDivVisible = false
$scope.Login = {
Username: '',
Password: '',
Error: '',
validateLogin: function () {
$scope.Login.Error = ''
$scope.DefaultProps.LoggedInUsername =
sessionStorage.getItem("LoggedInUsername")
$scope.DefaultProps.UserDivVisible =
sessionStorage.getItem("UserDivVisible")
$scope.Login.Username = $scope.Login.Password = ''
$location.path('/Home')
}
}
}])
The statements
$scope.DefaultProps.LoggedInUsername=sessionStorage.getItem("LoggedInUsername")
and
$scope.DefaultProps.UserDivVisible =sessionStorage.getItem("UserDivVisible")
are really changing the values of the properties in the "Default" controller but routing to an other view both the "Default" controller properties "LoggedInUsername" and "UserDivVisible" are gone.It looks like i may need to have both the above statements in every other view i'm going to navigate to.
Is there an other way?
"Default" view being the parent, the controller is invoked only once at the start of the application upon navigating to other view the "Default" controller is never invoked.
But if i reload any page by clicking "reload" on the browser or hitting "enter" on the URL i see the "Default" controller being invoked, which is what i want to happen when i'm also navigating to other view via angular routing.
For clarity, here is a simplified template:
<div ng-app="myProSupMod" ng-controller="DefaultController">
<div ng-show="DefaultProps.LoggedInUsername">
Welcome {{DefaultProps.LoggedInUsername}}
<button ng-click="LogUserOut()">Logout<button>
</div>
<ng-view></ng-view>
</div>
Make the controller lightweight:
app.controller("DefaultController", function($scope, LoginService) {
$scope.DefaultProps = LoginService.getProps();
$scope.LogUserOut = function () {
LoginService.logout();
};
})
With the functions inside a service, they can be called by any controller and they are encapsulated in a way that makes the code easier to understand, debug, and maintain.
I'm trying to access the $parent in my child controller but for some reason I have to access the Fifth $parent in order to get the actual $scope from the Parent controller, Any Ideas?
Parent Controller
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user',
function($scope, $rootScope, user) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = []
$scope.selectedCompanyIndex = undefined;
$scope.selectedCompany = undefined;
$scope.selectedTicketIndex = undefined;
$scope.selectedTicket = undefined;
}]);
Child Controller
angular.module('App')
.controller('HomeCompaniesTabController', ['$scope', 'Companies',
function($scope, Companies) {
$scope.loadCompanies = function () {
$scope.companies = Companies.query();
}
/**
* Init
*/
$scope.selectCompany = function (company, index) {
$scope.$parent.selectedCompanyIndex = index; //this doesnt work
$scope.$parent.$parent.$parent.$parent.$parent.selectedCompany = company; //this does, why?
console.log($scope);
}
if($scope.currentUser.security < 3) {
$scope.loadCompanies();
}
}]);
Home template
<div ng-include="'dist/templates/header.html'"></div>
<div class="container-fluid">
<div class="row">
<div class="col-xs-12">
company : {{selectedCompany}}
</div>
</div>
<tabset>
<tab ng-repeat="tab in tabs" heading="{{tab.heading}}">
<div ng-include="'dist/templates/' + tab.template" ></div>
</tab>
</tabset>
</div>
Child template
<div class="row-fluid" ng-controller="HomeCompaniesTabController">
<div class="col-md-3">
<h4>Lista de Empresas</h4>
<hr/>
<div class="list-group">
<a
href=""
class="list-group-item"
ng-repeat="company in companies"
ng-click="selectCompany(company, $index)">
<h4 class="list-group-item-heading">
{{company.name}}
</h4>
</a>
</div>
</div>
<div class="col-xs-9">
<div ng-show="selectedCompany">
<h4><b>{{selectedCompany.name}}</b></h4>
</div>
</div>
Based on the comments of charlietfl I came up with this simple service for sharing data
angular.module('App')
.factory('SharedData', [function () {
return {
}
}]);
Then I simply inject it in the controllers
angular.module('App')
.controller('HomeController', ['$scope', '$rootScope', 'user', 'SharedData',
function($scope, $rootScope, user, SharedData) {
$rootScope.currentNav = 'home';
$rootScope.currentUser = user.data;
$scope.sharedData = SharedData;
$scope.tabs = [
{
heading : 'Empresas',
template : 'home_companies_tab.html'
},
{
heading : 'Tickets',
template : 'home_tickets_tab.html'
}
];
$scope.companies = [];
}]);
I am new to angular js and the following code am using in my project here my problem is when i click on ng-click=addtocart(parameter) it is not responding the child controller.?how can i call the child controller ?please help me out?
<div ng-app="" ng-controller="parentCtrl">
<ul>
<li ng-click="search('12345');">
<div >
<div>
<div><img src="ProfileImges/menu.jpg"/></div>
<div>Hello</div>
</div>
</div>
</li>
</ul>
<div ng-repeat="x in names">
<div ng-click="addToCart('SMN1');">
<div>
<h4> {{ x.Price }} per meal</h4>
<img ng-src="{{x.ImgSrc}}"/>
</div>
<div>
<img ng-src="{{x.UserImg}}"/>
<p><strong>{{x.Uname}}</strong><br>
<span>{{x.RewPer}} </span><br>
</p>
</div>
<h4>{{x.Mtitle}}</h4>
<span><strong>{{x.Cuisine}}</strong></span>
<p`enter code here`>{{x.Mdesc}}</p>
</div>
</div>
<div ng-controller="childCtrl">
<div>{{cartdetails.name }}</div>
<div>Price</div>
</div>
</div>
<script>
var sj=angular.module('MyApp', []);
sj.controller('parentCtrl', ['$scope','$http', function($scope, $http) {
$scope.search = function(param) {alert("enter123");
$http.get('AngularJs-Response.jsp?mid='+param).success(function(response) {
$scope.names = response;
});
};
$scope.addToCart=function(smid){
CallAddCart(smid);
};
}]);
function CallAddCart(smid) {
sj.controller('childCtrl', ['$scope','$http', function($scope, $http) {
$http.get('reponse.jsp?smid='+smid).success(function(response) {alert(response);
$scope.cartdetails = response;
});
}]);
};
</script>
See plnkr: http://plnkr.co/edit/IdsHc19xBUalZoIXPE2T?p=preview
In a nutshell, you can communicate from parent to child controller by using the $scope as an event bus via the $broadcast and $on APIs:
angular.module("app", [])
.controller("ParentCtrl", function($scope) {
$scope.parentName = "parent";
$scope.onClick = function() {
$scope.parentName = "clicked";
$scope.$broadcast('onSearch', {myMsg: "hi children"});
}
})
.controller("ChildCtrl", function($scope) {
$scope.childName = "child";
$scope.$on('onSearch', function(event, obj) {
$scope.childName = obj.myMsg;
})
});
After onClick() is called on the parent, the parent $broadcasts the 'name' on the 'onSearch' channel to all its children. ChildCtrl is configured to listen on the 'onSearch' channel, once it receives a message, the callback function executes.
My view is:
<div class="container" ng-controller="MyController">
<div class="row">
<div class="col-md-8">
<textarea class="form-control" rows="10" ng-model="myWords" ng-change="parseLanguage()"></textarea>
</div>
<div class="col-md-4" ng-show="sourceLanguage !== null">
Language: {{ sourceLanguage }}
</div>
</div>
</div>
My controller is:
webApp.controller('MyController', [
'$scope', '$rootScope', 'TranslateService', function($scope, $rootScope, CodeService) {
$scope.init = function() {
return $scope.sourceLanguage = null;
};
$scope.parseLanguage = function() {
return TranslateService.detectLanguage($scope.myWords).then(function(response) {
console.log($scope.sourceLanguage);
$scope.sourceLanguage = response.data.sourceLanguage;
return console.log($scope.sourceLanguage);
});
};
return $scope.init();
}
]);
The console logs show the right data. But in the view, sourceLanguage never updates. Why would this be?
In case the promise you are evaluating is not part of the Angular context you need to use $scope.$apply:
$scope.parseLanguage = function() {
TranslateService.detectLanguage($scope.myWords).then(function(response) {
$scope.$apply(function() {
$scope.sourceLanguage = response.data.sourceLanguage;
});
});
};
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).