Angularjs why this html page(view) does not integrate with Angular - javascript

I have an Angularjs site that works. However one html file(view) does not integrate with Angular. The flight fields are not show and the button is not active.
Can anybody help?
<nav class="top-bar" data-topbar="" role="navigation">
<ul class="title-area">
<li class="name"><h1><a ui-sref="client.payment">Pagamento</a></h1></li>
</ul>
</nav>
<div id="sidePanelContent">
<a ui-sref="^" ui-sref-opts="{reload: true}" class="closeSidePanel"><img src="images/admin/botao-fechar.png" alt="Fechar"></a>
<h1>Pagamento do Voo</h1>
<div>
<p ng-show="flight"><strong>Voo:</strong> {{flight.fromairport.name}} ➝ {{flight.toairport.name}}</p>
<p ng-show="flight"><strong>Horário:</strong> {{flight.departure | formatDateTime}}h</p>
<p ng-show="flight"><strong>Lugares disponíveis:</strong> {{flight.availableseats}}</p>
<p ng-show="flight"><strong>Aeronave:</strong> {{flight.airplane.name}}</p>
<p ng-show="flight"><strong>Preço atual:</strong> R$ {{flight.price | formatPrice}}</p>
</div>
<button class="button" ui-sref="client.payment({flight:flightid})" >Pagar com Paypal</button>
---------------- Java script -----------------
'use strict';
/**
* #ngdoc function
* #name flyvipApp.controller:AboutCtrl
* #description
* # AboutCtrl
* Controller of the flyvipApp
*/
angular.module('flyvipApp')
.controller('PaymentCtrl', function ($scope, SharedData, $rootScope, $state, $stateParams, Authorization, $http) {
var api = "http://flyvip.com.br/app/api/";
var userid = Authorization.currentUser().user.id;
$rootScope.sidePanel = false;
SharedData.selectedMenu.setItem('voos');
$scope.menu = SharedData.selectedMenu;
$rootScope.homeClient = false;
$scope.orderedFlights = {data: []};
$scope.flag = false;
var _flightid = _id;
var _airplaneid = $scope.flight.airplane.id;
var _dateofdeparture = $scope.flight.dateofdeparture;
var _dateofarrival = $scope.flight.dateofarrival;
var _airportdeparture = $scope.flight.fromairport.id;
var _airportarrival = $scope.flight.toairport.id;
var _price = $scope.flight.price;
var _seats = $scope.flight.availableseats;
var _status = $scope.flight.flightstatus;
var _reason = $scope.flight.reason;
var flight = {
flightid: _flightid,
airplaneid: _airplaneid,
dateofdeparture: _dateofdeparture,
dateofarrival: _dateofarrival,
airportofdeparture: _airportdeparture,
airportofarrival: _airportarrival,
price: _price,
seats: _seats,
flightstatus: _status,
reason: _reason,
invoicenum: "122344",
passengerid: $scope.passengerid
};
$http({method: "POST", url: api + "DoWriteLog.php",msg:'Entrei neste script!', headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
});
$http({method: "POST", url: api + "DoPayment.php", data: flight, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(response, status, headers, config) {
if (response.success) {
$scope.flag = true;
}
else
$scope.flag = false;
})});

You are not assigning flight object to scope try this:
$scope.flight = {
...
}
Also I can see that most of the variables are not declared in that object except flight.fromairport.
I'm not sure where are you getting the data from, but make sure it is assigned to $scope.flight at some point.

Related

How to reduce redundant code using angularjs?

dt.html and st.html are exactly same only difference in controller is scoket.on call dtconsumer vs stconsumer , How can i use one controller for both views or same view and controller for two different state. there is alot of redundant code in js and html. what is best approach to resolve this issue ?
Do i need to write directive ?
dt.html
<div class="panel-body display-logs" scroll-bottom="event" style="width:100%;">
<ul style="list-style: none;">
<li ng-repeat="message in event | limitTo:1000" ng-class="{lastItem: $last}"><span>{{message.value}}</span></li>
</ul>
</div>
Ctrl-1.js
var searchEnv = 'DT';
$scope.event = [];
socket.on('dtConsumer',function (data) {
var obj = {
file:$scope.filename,
data:data
}
var messageSize = getBytesForBuffer(data);
$scope.event.push(data);
});
Ctrl-2.js
var searchEnv = 'st';
$scope.event = [];
socket.on('StConsumer',function (data) {
var obj = {
file:$scope.filename,
data:data
}
$scope.event.push(data);
var messageSize = getBytesForBuffer(data);
});
app.js
.state('app.dt', {
url: '/dt',
templateUrl: 'view/partials/dt.html',
controller: 'DitCtrl'
})
.state('app.st',{
url:'/st',
templateUrl:'view/partials/st.html',
controller:'StCtrl'
})
You could pass dt/st via $stateParams, so you could keep 1 url with dt/st as a parameter. Something like this.
app.js
.state('app.dt', {
url: '/:type',
templateUrl: 'view/partials/dt.html',
controller: 'DitCtrl'
})
ctrl.js
var searchEnv = $stateParams.type;
$scope.event = [];
socket.on(searchEnv+'Consumer',function (data) {
var obj = {
file:$scope.filename,
data:data
}
var messageSize = getBytesForBuffer(data);
$scope.event.push(data);
});

AngularJS insert data twice to database

I am trying to insert data to database through angularJS but the data inserted twice.. I have tried to use ngRoute but still I face the same problem.
app.js
var app = angular.module("addDepApp", []);
app.controller('insertDepCtl', function($scope, $http) {
var isSend = false;
$scope.$on('newuser', function(event, data){
load(true);
});
var load = function(isEvent){
if($scope.$parent.newuser != null){
isSend = true;
}
};
load();
$scope.insertDepartment = function () {
console.log("called insertDepartment");
if (isSend == true){
$scope.newuserSend = {'org_id': $scope.$parent.newuser.org_id, 'dep_name': $scope.department};
$http.post("http://192.168.1.12:8888/XXXX/XXX/insertDep.php/",$scope.newuserSend)
}
}
});
add.html
<body ng-app="addDepApp">
<div class="12u$" ng-controller="insertDepCtl">
<input type="button" value="تسجيل" class="special" id="signup" ng-click="insertDepartment()"/>
</div>
</body>
Remove ng-controller="insertDepCtl" from your html code, your router injects this for you. Right now, you're calling everything twice
I have changed the code to this and now it works fine!!
$scope.insertDepartment = function () {
if (isSend == true) {
var request = $http({
method: "post",
url: "http://192.168.1.106:8888/XXXX/XXX/insertDep.php/",
data: {'org_id': $scope.$parent.newuser.org_id, 'dep_name': $scope.department},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
}
}

Not able to obtain value in view (directive)

I have an array in the profile-form.html directive's controller.
But I am neither able to obtain the value of that array (all_languages) nor iterate over it using ng-options in the directive. It's simply printing as string. I am new to Angular and maybe doing everything terribly wrong.
Directive
app.directive("profileForm", function() {
return {
restrict: "E",
templateUrl: "/static/translatorNgApp/profile-form.html",
controller: ['$scope','$http',function($scope, $http) {
this.getCookie = function(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
console.log(cookieValue);
return cookieValue;
};
$scope.csrftoken = this.getCookie('csrftoken');
$scope.myForm={};
$scope.all_languages = ['English', 'Hindi'];
$scope.language_pairs = [];
$scope.getAllLanguages = function () {
$http.get('/getAllLanguages'
).success(function(response) {
// success
$scope.all_languages.concat(response);
}).error(function(response) {
// failed
});
};
$scope.submitForm = function() {
var postData = {
method: 'POST',
url: '/accounts/tprofile/',
// headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
headers: {'X-CSRF-Token' : $scope.csrftoken },
data: $scope.myForm
};
$http(postData)
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
console.log("Form submitted");
// $scope.message = "Sent Successfully 2";
// console.log(postData);
console.log(postData);
console.log($scope.myForm);
};
$document.ready(function(){
console.log("document ready");
$scope.getAllLanguages(); //This can be commented out for the question's sake.
});
}],
controllerAs: "profileFormCtrl"
};
});
Directive Template (profile-form.html)
<div class="form-group" >
<label for="id_source_language">Source language: </label>
<ul>
<li>
<pre>all_languages = {{all_languages | json}}</pre>
<select data-ng-model="source" ng-options="language for language in all_languages" class="form-control" id="id_source_language" name="source_language" placeholder="Source Language" required>
</select>
<button ng-click="language_pairs.pop($index)" aria-label="Remove">Remove</button>
<button ng-click="language_pairs.push({})">Add more pair</button>
</li>
</ul>
</div>
Using document.ready event inside a angular directive doesn't make sense to call specific method of scope. Because document.ready event has already happened after that event only angular started process page.
Ideally to make your code working state you need to remove $document.ready(function(){ .... }); code which isn't required there. And as document.ready is already accomplished, so the one which you had registered from directive wouldn't get call.

Prevent ng-repeat until request data is fully loaded

Im trying to prevent ng-repeat runs before the request data is fully loaded into an array, I've done it using a timeout but it only works when the request takes less than I say
Here is my HTML:
<div class="blocks-container" ng-init="loadProjects()" ng-controller="buildMonitorController">
<div class="row">
<!-- <div> -->
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2 block animate"
ng-if="!errorDialogActive && finishedRequest"
ng-repeat="build in builds.builds.build track by build._id | orderBy:'lastBuildDetails.startDate' : true"
ng-class="{'running': project.running ,'block-green': build._status ==='SUCCESS','block-red': build._status==='FAILURE'}"
id="{{build._id}}">
<div class="title-container"><p>{{build._buildTypeId}}</p></div>
<div class="update-container col-xs-12">
<time>{{ build.lastBuildDetails.startDate | date : 'dd.MM.yyyy H:mm:s'}}</time>
</div>
</div>
<!--</div>-->
</div>
<!-- Start error state dialog -->
<div ng-include src="'views/main/error-dialog.html'"></div>
And Here is my AngularJS:
$scope.refreshBuilds = function () {
$scope.errorList.length = 0
//#TODO remove this part right after the API is working
//Init
var suffix = '';
var randomnumber = Math.floor(Math.random() * 3);
//simulate mock by random number
switch (randomnumber) {
case 1:
suffix = '-success';
break;
case 2:
suffix = '-less';
break;
default:
break;
}
var url = 'mock/builds'+suffix+'.xml';
console.log('url: ' + url)
$http({
method: 'GET',
url: url,
headers: {
Authorization: 'Basic AAA'
}
}).success(function (data, status) {
//Recive builds from xml and reset scope
var buildsToFilter = new X2JS().xml_str2json(data);
$scope.errorDialogActive = false;
//filter builds which have a no build API detail status
if (buildsToFilter.builds.build !== undefined) {
angular.forEach(buildsToFilter.builds.build, function (build, index) {
$http({
method: 'GET',
url: 'mock/build-'+build._id+'.xml',
headers: {
Authorization: 'Basic AAA'
}
}).success(function (buildDetailData) {
$scope.errorDialogActive = false;
//push detail data into build array
buildsToFilter.builds.build[index].lastBuildDetails = new X2JS().xml_str2json(buildDetailData).build;
console.log(buildsToFilter.builds.build[index]);
}).error(function (data, status) {
$scope.errorDialogActive = true;
//remove build from index if no build detail was found
buildsToFilter.builds.build.splice(index, 1);
$scope.setError(status, '', '');
}).then(function () {
//after filtering builds to display, setup builds $scope for FrontEnd
$scope.builds = buildsToFilter;
});
});
} else {
}
}).error(function (data, status) {
//active dialog if error happens & set error
$scope.errorDialogActive = true;
$scope.setError(status, 'builds', '');
}).then(function () {
$timeout(function () {
$scope.finishedRequest = true;
}, 5000);
//refresh right after proceed and a little delay
$timeout(function () {
console.log('Starting refresh');
$scope.refreshBuilds();
}, 21000);
})
};
You can put condition
ng-show=builds.builds.build.length > 0
So when the builds.builds.build have data then only it will be displayed
You already have that
ng-if="!errorDialogActive && finishedRequest"
in place, but you never set $scope.finishedRequest = false. What if you simply modify your refreshBuilds function like this:
$scope.refreshBuilds = function () {
$scope.finishedRequest = false;
$scope.errorList.length = 0;
// etc
Does it work then in the way you wanted?

How to append/display/render data to page on click

I want to get the data from the API and display it on my index.html page. What's the best way in doing this? looking for multiple ways, that be jquery or data binding with angular. I can't seem to figure out a function to display the data I get. I'm fetching two different datas from two different players and I want to display them side by side. JSON data is returned by the API
/**Part of Index.html**/
<body ng-app="lolvs" ng-controller="MainController">
<div class="throwdown">
<h1> LoL THROWDOWN </h1>
<div class="summonerNames">
<input id="summonerOne" ng-model="summonerOne" placeholder="summoner name">
<button class="start" ng-click="start()">vs</button>
<input id="summonerTwo" ng-model="summonerTwo" placeholder="summoner name">
</div>
/**app.js**/
(function(){
'use-strict'
var mainCtrl = function mainCtrl($scope, $rootScope, MainFactory) {
$scope.start = MainFactory.start;
$rootScope.$on('gotStats', function (e, m) {
console.log('arguments >>', arguments);
$scope.player1 = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
$scope.apply();
});
};
var mainFactory = function ($http, $rootScope) {
var api = 'api_key=***************************';
var add = function(data, status, headers) {
var stats = {
totalChampionKills : 0,
totalDeathsPerSession : 0,
totalAssists : 0,
totalSessionsWon : 0,
totalSessionsLost :0,
totalMinionKills: 0,
totalTurretsKilled: 0,
};
var champions = data.champions;
for(var i = 0; i < champions.length; i++) {
var champ = champions[i].stats;
for(stat in stats) {
if(champ[stat]) {
stats[stat] += champ[stat]
}
}
}
};
var start = function(name) {
var options = {
url: 'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + name + '?' + api,
type: 'GET',
success: summonerOption
};
$http(options);
};
var summonerOption = function(data, status, headers) {
var name = Object.keys(data)[0];
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: add
};
$http(newOption);
};
return {
start: start
}
};
angular.module('lolvs', [])
.controller('MainController', ['$scope', '$rootScope', 'MainFactory', mainCtrl])
.factory('MainFactory', ['$http', '$rootScope', mainFactory])
})();
What kind of data is being returned? If it is a json array, you might want to iterate through it before printing the whole thing to your webpage.
In theory however, you should handle the data after a successful ajax call, which seems to be executed after pressing the <button> in your index.html..
This could look like so:
var newOption = {
url: 'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' + data[name].id + '/ranked?season=SEASON4&' + api,
type: 'GET',
success: function(data) {
$('.containerForData').html('<div class="data-wrap">' + data + '</div>');
}
};
Unfortunately your question is not very clear, but I hope this helps.

Categories

Resources