AngularJS ng-if does not work - angularjs

In the controller, I have this
var onComplete = function(response)
{
$scope.reportList = response.data;
$log.info($scope.reportList);
};
In the HTML, reportList is a JSON like this {packageType=1, salary=12900 }.
ReportList is not an array {{ reportList.packageTypeId }} return 1
The issue is with ng-if div
<div class="exceptionProcedure" ng-if=" reportList.packageType == 1">
<a> display package 1 </a>
when I tried this, it still does not work
<div class="exceptionProcedure" ng-if=" {{reportList.packageType}} == 1">
<a> display package 1 </a>
Any ideas?

You need to define reportList.packageType on the initial page load so that it links between your controller and view:
$scope.reportList = {}
var onComplete = function(response) {
$scope.reportList = response.data;
$log.info($scope.reportList);
};
This way, you'll only have one version that is shared between controller and view. The way you're doing it now creates two separate versions.

Related

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();

How to trigger the click event inside ng-repeat of angularjs?

I am doing the ng-repeat for showing the project list in my app. on click on the individual project I need to show the list of surveys inside the project. But when the page get loaded for first time I want to trigger the click event of first project which is default.
Below is the html code for that list project.
projectlist.html
<ul class="sidebar-nav">
<li class="sidebar-brand" >
<a>
Projects
</a>
</li>
<li ng-repeat="obj in allProjects track by $id(obj)">
<a ui-sref="survey.surveyList({id: obj.ProjectID})" ng-click="getProjSurveys(obj.ProjectID)" data-id="{{obj.ProjectID}}">{{obj.ProjectName}}<span class="projectsetting"><img src="./images/settings.png"/></span></a>
</li>
</ul>
ctrl.js
require('../styles/survey/survey.less');
angular.module("adminsuite").controller("surveyController",['getAllSurveyService','$timeout','AuthenticationService', '$scope','$rootScope', '$state', '$stateParams', function(getAllSurveyService,$timeout, AuthenticationService,$scope,$rootScope,$state,$stateParams){
$rootScope.header = "survey";
$scope.hoverIn = function(){
this.hoverEdit = true;
};
$scope.hoverOut = function(){
this.hoverEdit = false;
};
$rootScope.surveySelected = false;
console.log($('.checked').length);
console.log($('.checkbox').length);
if($state.current.name != 'login'){
$rootScope.bgGround = 'bgBlank';
$rootScope.footerbgGround = 'bgFooter';
}
$scope.supported = false;
$scope.wapLink = 'http://apidev.1pt.mobi/i/interview?uid=188A80CF0D61CA60D2F5_495F23E0FD4B9120D1E7&surveyid=20903';
$scope.success = function ($event) {
$scope.supported = true;
console.log($(".copied"));
};
$scope.fail = function (err) {
console.error('Error!', err);
};
getAllSurveyService.surveyList().then(
function( data ) {
$scope.allProjects = data;
$scope.allSurveys = data[0].Surveys;
if($scope.allSurveys.ErrorMessage){
AuthenticationService.ClearCredentials();
}
}
);
$scope.getReportDetails = function(){
return $http.get('http://localhost:8395/api/UserSurvey/GetAllSurveys', {
headers: { 'Content-Type': 'application/json','SessionID':$rootScope.token}
})
};
$scope.getProjSurveys = function(projId){
var i;
for(i in $scope.allProjects){
if(projId == $scope.allProjects[i].ProjectID){
$scope.allSurveys = $scope.allProjects[i].Surveys;
}
}
angular.element(document.querySelectorAll(".surveymodule")).removeClass('toggled');
};
$scope.toggleClass = function($event){
angular.element($event.target).toggleClass("checked");
$rootScope.selectedItems = angular.element(document.querySelectorAll(".checked")).length;
angular.element($event.target).parent().toggleClass("active");
if(angular.element(document.querySelectorAll(".checked")).length < 1){
$rootScope.global.showNewHeader= false;
};
};
}]);
on-click of the projects I am able to show data in the ui-view but for the first time on load of the page unable to trigger click event for the first project. I tried with the above code inside the controller using angular.element and trigger('click'), but it is not working for me. Please help.
This is actually angularjs issue. JQuery's trigger click event not getting triggered in angular's ng-repeat.
Check this : https://github.com/angular/angular.js/issues/3470
The problem is you are using ui-sref along with ng-click. Here the state is changing before the function completes and either reloading the controller (if both states has same controller) or changing the controller. Hence ng-click finction is not running.
remove ui-sref and use $state.go() to change the state inside ng-click
Sample code here:
HTML
<ul class="sidebar-nav">
<li class="sidebar-brand" >
<a>
Projects
</a>
</li>
<li ng-repeat="obj in allProjects track by $id(obj)">
<a ng-click="getProjSurveys(obj.ProjectID)" data-id="{{obj.ProjectID}}">{{obj.ProjectName}}<span class="projectsetting"><img src="./images/settings.png"/></span></a>
</li>
</ul>
JS:
$scope.getProjSurveys(objId){
// your codes here
$state.go('survey.surveyList({'id': objId})')
}
Instead of trying to interact with the DOM you should do something like this:
getAllSurveyService.surveyList().then(
function( data ) {
$scope.allProjects = data;
$scope.allSurveys = data[0].Surveys;
$scope.getProjSurveys($scope.allProjects[0].ProjectID)
if($scope.allSurveys.ErrorMessage){
AuthenticationService.ClearCredentials();
// $state.go('login');
}
});

How to get value in another controller - Angular JS

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

How to call $scope.$apply() using "controller as" syntax

I am trying to limit my use of $scope in my controllers as much as possible and replace it with the Controller as syntax.
My current problem is that i'm not sure how to call $scope.$apply() in my controller without using $scope.
Edit: I am using TypeScript 1.4 in conjunction with angular
I have this function
setWordLists() {
this.fetchInProgress = true;
var campaignId = this.campaignFactory.currentId();
var videoId = this.videoFactory.currentId();
if (!campaignId || !videoId) {
return;
}
this.wordsToTrackFactory.doGetWordsToTrackModel(campaignId, videoId)
.then((response) => {
this.fetchInProgress = false;
this.wordList = (response) ? response.data.WordList : [];
this.notUsedWordList = (response) ? response.data.NotUsedWords : [];
});
}
being called from
$scope.$on("video-switch",() => {
this.setWordLists();
});
And it's (the arrays wordList and notUsedWordList)
is not being updated in my view:
<div class="wordListWellWrapper row" ng-repeat="words in wordTrack.wordList">
<div class="col-md-5 wordListWell form-control" ng-class="(words.IsPositive)? 'posWordWell': 'negWordWell' ">
<strong class="wordListWord">{{words.Word}}</strong>
<div class="wordListIcon">
<div class="whiteFaceIcon" ng-class="(words.IsPositive)? 'happyWhiteIcon': 'sadWhiteIcon' "></div>
</div>
</div>
<div class="col-md-2">
<span aria-hidden="true" class="glyphicon-remove glyphicon" ng-click="wordTrack.removeWord(words.Word)"></span>
</div>
</div>
Along the same lines of $apply, is there another way of calling $scope.$on using Controller as?
Thanks!
To answer the question at hand here, you can use $scope() methods in a controller when using the controller-as syntax, as long as you pass $scope as a parameter to the function. However, one of the main benefits of using the controller-as syntax is not using $scope, which creates a quandary.
As was discussed in the comments, a new question will be formulated by the poster to review the specific code requiring $scope in the first place, with some recommendations for re-structuring if possible.

Onclcik ng-show not showing the data in accordion using angularJS and Ionic?

I have tow api one return clinics list and another is onclcik take the clinic id and call the api and display the data to that particular id in accordion list.
But by using ng-show, I am unable to show the data.
Here is my code:
Html code:
<ion-list id = "background">
<div id = "background" >
<ion-item class="item-stable item item-avatar" ng-click = "select(list.ClinicId);" ng-repeat="list in searchlist">
<img ng-src = "img/1.png"/>
<!-- -->
{{list.Name}}
<p> Address: {{list.Address.Address1}}, {{list.Address.Address2}}, {{list.Address.Postcode}}, {{list.Address.State}}, {{list.Address.Suburb}}</p>
</ion-item >
<ion-item class="item-accordion" ng-show="isSelected();" ng-repeat="available in appointments" >
{{available.Appointments.Name}} {{available.Appointments.Speciality}}
</ion-item>
</div>
</ion-list>
JavaScript Code:
$scope.select = function(item) {
api.AvailableAppointments(item)
.success(function(data) {
$scope.availableappointments = data;
console.log(data);
window.sessionStorage['availableappointments'] = angular.toJson(data);
var appointments = window.sessionStorage['availableappointments'];
})
.error(function(data) {
console.log(data);
});
};
$scope.isSelected = function() {
var appointments = window.sessionStorage['availableappointments'];
$scope.appointments = angular.fromJson(accessData);
console.log($scope.appointments);
};
please tell me where I am going wrong....
It would have been great to have a plunker document join to your question but I might an idea why it doesn't work.
Your isSelected() function return nothing that might be why it doesn't change.
Try to add the $index as an argument of your function and compare it to the active clinicID (the one that has been clicked ) then return the answer.
.html
<ion-item class="item-accordion" ng-show="isSelected($index);" ng-repeat="available in appointments" >
{{available.Appointments.Name}} {{available.Appointments.Speciality}}
</ion-item>
.js
$scope.isSelected = function(itemIndex) {
var appointments = window.sessionStorage['availableappointments'];
$scope.appointments = angular.fromJson(accessData);
console.log($scope.appointments);
return (itemIndex == itemSelectionnedIndex);
};
If it doesn't work if ng-show try with ng-if
Edit :
I try to adapt your code on the example that you gave me :
http://codepen.io/anon/pen/wdjAn
You only have to adapt the code to make hide the second accordion when you click a second time.
But it should work...
And your main problems (from what I saw in your code) was that you isSelected returned nothing and your appointments variable is not a list.
Hope it would solve your problem.

Resources