How to get value in another controller - Angular JS - angularjs

I am creating some divs using ng-repeat.
See code below :
.controller('meditationsController', function ($scope, $state, $rootScope, $http) {
var req = {
method: 'POST',
url: 'http://example.com/demo/',
headers: {
'Content-Type': 'application/json'
}
}
// Call API
$http(req).then(function(result) {
var rawData = result.data;
$scope.meditationByCategory = {};
for (var i = 0; i < rawData.length; i++) {
var meditation = rawData[i];
if ($scope.meditationByCategory[meditation.main_title] == undefined) {
$scope.meditationByCategory[meditation.main_title] = {};
$scope.meditationByCategory[meditation.main_title].name = meditation.main_title;
$scope.meditationByCategory[meditation.main_title].meditations = [];
}
$scope.meditationByCategory[meditation.main_title].meditations.push(meditation);
}
});
})
<div ng-repeat="(categoryName, category) in meditationByCategory">
<div class="peacefulness"><p class="para-text">{{category.name}}</p></div>
<a href="" ng-click="goToDetailPage()" class="customlink">
<div class="item-content" ng-repeat="meditation in category.meditations">
<span class="leftSpanStyle">{{meditation.title}}</span>
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
</div>
</a>
</div>
I have successfully created the list of divs dynamically according to service response.
Now i want to apply click to each div. and the data that i am getting in service response want to bind the next page. I mean the data on the next page will be dynamic and depend upon cliked div.
please help me to bind the data into another page..

Add a button to your view. Something like:
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
<button ng-click="doSomeThing($index)"></button>
And in your controller:
$scope.doSomeThing = function(index){
//do something with category.meditations[index]
//or go to another state: $state.go("myState", {item: category.meditations[index]})
}
Edit:
As you say "want to bind to next page" I assume that you want to navigate to another page. Assuming also that you do so by using angulars ui-router, that means that you want to change state. In that case don't forget to define:
url: /myUrl/:item
for that state in question. You can access the item in the target state / controller with $stateParams.item

Related

How to pass selected id in url through AngularJS routing and get data in console.log?

Im Passing Selected Car Id in Url and trying to get data in console.log don't know where i'm missing may be i'm confused checking too much solution in stackoverflow - here is my code :
//Controller.js
$scope.chooseACar = function(selectCarId)
{
$scope.selectCarId = $stateParams.selectCarId;
console.log($scope.selectCarId);
}
//App.js
.state('main.step3',
{
url: '/step2/:selectCarId',
templateUrl: 'pages/step3.html'
});
//services.js
get: function(selectCarId) {
for (var i = 0; i < carListData.length; i++) {
if (carListData[i].id === parseInt(selectCarId)) {
console.log(carListData[i]);
return carListData[i];
}
}
return null;
}
// HTML Code
<a type="submit" href="#/main/step2/{{selectCarList.id}}" class="button button-yellow button-full submitBtn" style="color:#000; display:block">CHOOSE A CAR</a>
In App.js (if you are getting ID in url no need to modify.)
.state('main.step2', {
name: 'slectcarID'
url: '/step2/:selectCarId',
templateUrl: 'pages/step3.html'
});
and to get the data in controller use $stateParams
console.log($stateParams.selectCarId);
or
$scope.selectCarId = $stateParams.selectCarId;
console.log($scope.selectCarId);
Try either only ng-click or ui-sref
Try using ui-sref instead of href
HTML
<a type="submit" ui-sref="main.step3({carId : selectCarList.id})"
class="button button-yellow button-full submitBtn"
style="color:#000; display:block">CHOOSE A CAR
</a>
App.js
.state('main.step3',
{
url: '/step2/:selectCarId',
templateUrl: 'pages/step3.html',
controller: `Your Controller Name`,
params: { carId: null, }
});
Controller
$scope.chooseACar = function(){
$scope.selectCarId = $stateParams.carId;
console.log($scope.selectCarId);
}

how to Dynamically Active tab with content for ui bootstrap tabs in angularjs?

I want to dynamically active tab with content in angular js
my code is
<uib-tabset ng-if="pets_count > 0" class="petsTabs tab-animation">
<div ng-repeat="(key, pet) in pets_list">
<uib-tab heading="{{pet.pet_name}}" active="{{pet.pet_id == activePet}}">
<div class="petsTabsContent" >
<h4>
{{pet.pet_name}}
<small>
Boarding Dates: {{ pet.start_date | date : 'MMMM d, y'}} to {{ pet.end_date | date : 'MMMM d, y'}}
</small>
</h4>
</div>
</uib-tab>
</div>
</uib-tabset>
i have two variables pet.pet_id, activePet on base for these variables i have to active tab.
but it does not working i am new to angular js
thanks in advance
This controller
$scope.show_pet_function = function () {
var pet_id;
var action;
pet_id = parseInt($('.pet_view_option').attr('data-pet_id'));
action = $('.pet_view_option').attr('data-action');
petowner_user_id = parseInt($('.pet_view_option').attr('data-pet-owner'));
var details = $scope.hidePetData;
$http.post(CONFIG.APIURL + 'Pets/changePetHideStatus/', {pet_id: pet_id, action: action})
.then(function (response) {
if (response.data.action == 'show_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
toastr.success(response.data.message);
} else if (response.data.action == 'hide_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
}
});
}
This is response for pet_list object type array
I think there might be an issue with $scope binding, as you are pulling the data in then-able function.
So try by placing $scope.$apply() after the $http response.
For reference add it like this
angular.extend($scope.pets_list, response.data['pets_list']);
$scope.$apply();

html data get from $http GET is not showing properly in Angular js..?

I have defined a controller like this :
app.controller("home", function ($scope, $http, $common) {
$http({
method: "GET",
url: '/posts/loadData'
}).then(function (response) {
//console.clear()
if (typeof response.data.posts != 'undefined') {
console.log(response.data.posts);
$scope.posts = $common.arrangePosts(response.data.posts);
}
});
})
and a service to arrange data :
app.service('$common', function ($timeout, $sce, $httpParamSerializerJQLike) {
var that = this;
this.arrangePosts = function (rawPosts) {
var posts = [];
$.each(rawPosts, function (key, value) {
posts.push({
postId: value.postId,
postLink: '/post/' + that.cleanString(value.title) + '/' + value.postId,
title: value.title,
summary: $sce.trustAsHtml(value.summary)
});
});
return posts;
}
});
using values in html like this :
<div class="widget fullwidth post-single">
<h4 class="widget-title">Latest</h4>
<div class="widget-content">
<ul>
<li ng-repeat="post in posts">
<h4 class="list-title">{{post.title}}</h4>
{{post.summary}}
</li>
</ul>
</div>
</div>
Data coming from server in JSON form :
Object { postId="4", title="asdf", summary="<p>asdf</p>"}
but all the html tags are printing on my page as it is (like a text) in summary.
In many SO posts people suggested to use $sce.trustAsHtml but its not working for me. Please suggest anyway to solve my problem.
Any help will be appreciated..!!
have you tried this?
<div ng-bind-html='post.summary'></div>
You could solve this over a directive. Did you know, that you can use JQuery Lite inside AngularJS to manipulate the DOM?
Here a quick example:
angular.module("PostsDirective",[])
.directive("posts", function($sce){
return {
link: function($scope, $element, $attrs){
//the HTML you want to show
var post = "<div>hello world</div>";
var posts = [post,post,post,post];
//iterating through the list (_.each is a function from underscore.js)
_.each(posts, function(element){
//if you want to save the trusted html string in a var you can do this with getTrustedHtml
//see the docs
var safeHtml = $sce.getTrustedHtml($sce.trustAsHtml(element));
//and here you can use JQuery Lite. It appends the html string to the DOM
//$element refers to the directive element in the DOM
$element.append(safeHtml);
});
}
};
});
And the html
<posts></posts>
This also pretty nice for the readability for your HTML code. And you can use it everywhere on your page.
BTW:
As i can see, you get the HTML elements directly from a REST-Service. Why don't you get just the data and insert it into the ng-repeat? If you transfer all the HTML you get a pretty high overhead if you have loads of data.

angular ng-repeat to always show even on empty object

Hi I want to post item to server, and with each successful addition, automatically add it to DOM with ng-repeat
<div class="" ng-repeat="book in books" >
<div id="eachBook">{{book.title}}</div>
</div>
to POST the data and also to upload an image file, I use Jquery ajax, and $state.go(".") to reload the current page:
var fd = new FormData();
fd.append("file", bookImage);
$http({
method: 'POST',
url: "/someurl,
data: fd,
headers: {
'Content-Type': undefined
}
}).success(function(Image){
var book_obj = {
bookTitle: bookTitle,
bookImage: Image._id
};
$http.post("url to owner book", book_obj)
.success(function(data){
$scope.bookImage = data.bookImage;
$timeout(function(){
alert("success", "successfully added your book");
$state.transitionTo('book', {}, { reload: true });
},2000);
})
})
The problem is with first addition, the DOM is still empty, and even though I use $state to reload the page, it still not working for the first addition. In the end I need to refresh the page manually by clicking refresh.
after the first addition, it works fine. With each book added, it automatically added to DOM..
Any idea how to automatically start the first one without manually rendering the page? using $timeout to delay the refresh has no effect.
Is it not just a simple post to list on success?
var app = angular.module('myApp', []);
app.controller('bookCtrl', function($scope, $http, $timeout) {
$scope.init = function(){
$scope.title = 'initial book?'
postBook();
};
$scope.books = [];
$scope.post = function() {
postBook();
};
function postBook(){
if (!$scope.title) return;
// timeout to simulate server post
$timeout(function() {
$scope.books.push({title:$scope.title});
$scope.title = null;
}, 1000);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="bookCtrl" ng-init="init()">
<div class="" ng-repeat="book in books">
<div class="eachBook">{{book.title}}</div>
</div>
<input type="text" ng-model="title" /><button ng-click="post()">save</button>
</div>
EDIT: Not sure why your DOM isn't ready but how about ng-init to accomplish an initial book post?

Why the value couldn't show in the view after communicate between two controllers?

I met this problem again.Could anybody help me with this?
the first view:
<a type="button" ui-sref="index.usermng.userInfo" ng-click="checkUserInfo(item.id)" class="btn btn-primary">CheckUser</a>
the first controller:
$scope.checkUserInfo = function(userId) {
$rootScope.$broadcast('toUserInfo', userId);
}
the second view:
<div class="tab-pane active tab-chrome" id="tab-chrome">
<div class="row feature">
<div class="col-md-12">
<ul class="list-group">
<li class="list-group-item">UserId:{{data.user.userId}}</li>
<li class="list-group-item">Name:{{data.user.name}}</li>
<li class="list-group-item">Sex:{{data.user.sex}}</li>
<li class="list-group-item">Birthday:{{data.user.birthday | date:'yyyy-MM-dd'}}</li>
<li class="list-group-item">Mobile:{{data.user.mobile}}</li>
</ul>
</div>
</div>
</div>
the second controller:
userApp.controller('userInfoCtrl', ['$scope', '$http', '$rootScope', 'serverUrl', function($scope, $http, $rootScope, serverUrl) {
$rootScope.$on('toUserInfo', function(event, userId) {
console.log(userId); //i can get userId here
$http.get(serverUrl + "/user/info?userId=" + userId).success(function(data) {
console.log(data); // i can get data here
//if (data.code == 0) {
// $scope.detailUserID = userId;
// $scope.detailUserName = data.data.user.name;
// $scope.detailSex = data.data.user.sex;
// $scope.detailBirthday = data.data.user.birthday;
// $scope.detailMobile = data.data.user.mobile;
// $scope.detailCash = data.data.accumulate.usableCash;
$scope.data = data.data
}
//can't show in the view
})
})
}])
the config:
.state('index.usermng.userInfo',{
url: '/userInfo',
templateUrl: 'tpls/userInfo.html',
controller: 'userInfoCtrl'
})
In the second controller,I can get userId from the first controller,and I can get the data,but the view shows nothing,where is wrong?
This is a well known pitfall of Angular. It has to do with the fact that in the template the value is not updated because the scope variables are passed as values and that happens only once, when your view is rendered. That is normal Javascript behaviour.
The way around it is to place all the values on an object. I suggest you do this in your controller:
$scope.data = data.data
and in your templates you change it like this:
<li class="list-group-item">Name:{{data.user.name}}</li>
and so on
A good rule of thumb here is: if there is no dot in the variable in the template, then there is something wrong.
BTW, a more favourable approach is to use controllerAs, which forces you to use a dot in variable names in the template

Resources