AngularJS href is not getting dynamic value - javascript

javascript code:
cable.register.controller('VideoMonitorCtrl', ['$scope', '$sce','ENV', '$http', function ($scope, $sce, ENV, $http) {
console.log('Begin in video monitor controller');
var keepGoing =true;
var url = '/ps/features/';
var exists = false;
$scope.getVideoService = function () {
console.log("url"+$scope.hurl)
$http.get(url,{headers: {'contentType': 'application/json; charset=UTF-8'}}).success( function(response) {
if(response!='')
{
angular.forEach(response.features, function(feature){
console.log("in for each");
console.log(counter++)
if(keepGoing)
{
if(feature.name.trim() === "odl-video-monitor" && feature.installed.trim() ==='x')
{
console.log('in active again');
$scope.color='#FFFFFF';
$scope.msg='Quality Network';
$scope.hurl='index.html#/cable/videomonitor';
exists=true;
keepGoing = false;
}
}
});
if(!exists)
{
$scope.color='#BDBDBD';
$scope.msg='Video Quality Network is under maintenance';
}
}
else
{
$scope.color='#BDBDBD';
$scope.msg='Video Quality Network is under maintenance';
}
}).error(function (response) {
$scope.color='#BDBDBD';
$scope.msg='Video Quality Network is under maintenance';
});
};
}
]);
HTML code:
<a ng-href='{{hurl}}' ng-controller="VideoMonitorCtrl" ng-init="getVideoService()" id="hlink" style="text-decoration:none;">
<div class="box" style="background-color:{{color}};">
<div style="margin-top:15px;text-align:left;padding-left:23px;">
<span style="font-size:24px !important;font-family:Times New Roman, serif;color:#7B7B7B;" class="Large">{{msg}}
{{hurl}}
</span>
</div>
</div>
</a>
Output:
{{hurl}} => is printing the value in the div.
<a href={{hurl}} => there is not value in hurl here and link is not enabled.
Any reason? i am able to see the hurl content in the div but not in href?
If i write hardcoded value in href it is working but not dynamic?

Wrap the whole <a> element in another element and put the controller there, the scope of your VideoMonitorCtrl does not cover the <a> tag itself.
<div ng-controller="VideoMonitorCtrl" ng-init="getVideoService()">
<a ng-href='{{hurl}}' id="hlink" style="text-decoration:none;">
<div class="box" style="background-color:{{color}};">
<div style="margin-top:15px;text-align:left;padding-left:23px;">
<span style="font-size:24px !important;font-family:Times New Roman, serif;color:#7B7B7B;" class="Large">{{msg}}
{{hurl}}
</span>
</div>
</div>
</a>
</div>

Related

View not updating when splicing user from list in AngularJS

I have this problem in my app, when I use slice to remove the user from the list. However, it does not remove from the list. I am getting the user with a API url call. But for some reason, it does not remove the user from the list. Please, have a look at my code. If, you guys want the full code, I have put it in my github. I hope we both can solve this. Thank you in advance.
Here is my code:
<div ng-controller="MyCtrl">
<div ng-repeat="person in userInfo.lawyers | filter : {id: lawyerId}">
<a class="back" href="#/lawyer">Back</a>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="inactive = !inactive">Save</button>
<a class="delete" ng-click="confirmClick(); confirmedAction(person);" confirm-click>Confirm</a>
<div class="people-view">
<h2 class="name">{{person.firstName}}</h2>
<h2 class="name">{{person.lastName}}</h2>
<span class="title">{{person.email}}</span>
<span class="date">{{person.website}} </span>
</div>
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="person.firstName">
<br>
<b>Last Name:</b>
<input type="text" ng-model="person.lastName">
<br>
<b>Email:</b>
<input type="email" ng-model="person.email">
<br>
<b>Website:</b>
<input type="text" ng-model="person.website">
<br>
</fieldset>
</form>
</div>
</div>
</div>
App.js
var app = angular.module("Portal", ['ngRoute', 'ui.bootstrap' ]);
app.controller('MyCtrl', function($scope, $window) {
$scope.inactive = true;
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
};
});
app.directive('confirmClick', ['$q', 'dialogModal', function($q, dialogModal) {
return {
link: function (scope, element, attrs) {
// ngClick won't wait for our modal confirmation window to resolve,
// so we will grab the other values in the ngClick attribute, which
// will continue after the modal resolves.
// modify the confirmClick() action so we don't perform it again
// looks for either confirmClick() or confirmClick('are you sure?')
var ngClick = attrs.ngClick.replace('confirmClick()', 'true')
.replace('confirmClick(', 'confirmClick(true,');
// setup a confirmation action on the scope
scope.confirmClick = function(msg) {
// if the msg was set to true, then return it (this is a workaround to make our dialog work)
if (msg===true) {
return true;
}
// msg can be passed directly to confirmClick('Are you sure you want to confirm?')
// in ng-click
// or through the confirm-click attribute on the
// <a confirm-click="Are you sure you want to confirm?"></a>
msg = msg || attrs.confirmClick || 'Are you sure you want to confirm?';
// open a dialog modal, and then continue ngClick actions if it's confirmed
dialogModal(msg).result.then(function() {
scope.$eval(ngClick);
});
// return false to stop the current ng-click flow and wait for our modal answer
return false;
};
}
}
}])
/*
Modal confirmation dialog window with the UI Bootstrap Modal service.
This is a basic modal that can display a message with yes or no buttons.
It returns a promise that is resolved or rejected based on yes/no clicks.
The following settings can be passed:
message the message to pass to the modal body
title (optional) title for modal window
okButton text for YES button. set false to not include button
cancelButton text for NO button. ste false to not include button
*/
.service('dialogModal', ['$modal', function($modal) {
return function (message, title, okButton, cancelButton) {
// setup default values for buttons
// if a button value is set to false, then that button won't be included
cancelButton = cancelButton===false ? false : (cancelButton || 'No');
okButton = okButton ===false ? false : (okButton || 'Yes');
// setup the Controller to watch the click
var ModalInstanceCtrl = function ($scope, $modalInstance, settings) {
// add settings to scope
angular.extend($scope, settings);
// yes button clicked
$scope.ok = function () {
// alert("Lawyer is confirmed");
$modalInstance.close(true);
};
// no button clicked
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
// open modal and return the instance (which will resolve the promise on ok/cancel clicks)
var modalInstance = $modal.open({
template: '<div class="dialog-modal"> \
<div class="modal-header" ng-show="modalTitle"> \
<h3 class="modal-title">{{modalTitle}}</h3> \
</div> \
<div class="modal-body">{{modalBody}}</div> \
<div class="modal-footer"> \
<button class="btn btn-primary" ng-click="ok()" ng-show="okButton">{{okButton}}</button> \
<button class="btn btn-warning" ng-click="cancel()" ng-show="cancelButton">{{cancelButton}}</button> \
</div> \
</div>',
controller: ModalInstanceCtrl,
resolve: {
settings: function() {
return {
modalTitle: title,
modalBody: message,
okButton: okButton,
cancelButton: cancelButton
};
}
}
});
// return the modal instance
return modalInstance;
}
}])
app.config(function ($routeProvider) {
$routeProvider
.when("/lawyer", {
controller: "HomeController",
templateUrl: "partials/home.html"
})
.when("/lawyer/:id", {
controller: "LawyerController",
templateUrl: "partials/about.html"
})
.otherwise({
redirectTo: '/lawyer'
});
});
But the element is getting deleted from list right?
If yes then, Try this :
$scope.confirmedAction = function (lawyer) {
$scope.$apply(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
});
});
Or
$scope.confirmedAction = function (lawyer) {
$timeout(function () {
var index = $scope.userInfo.lawyers.indexOf(lawyer);
console.log($scope.userInfo.lawyers);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$state.go($state.current, {}, {reload: true});
// $window.location.href = '#/lawyer';
},1100);
});
The problem is that you don't get the index from IndexOf when you using it on an array of objects like you do. Read more about the IndexOf here.
Instead, use map and then use IndexOf on that
Try it like this:
$scope.confirmedAction = function (lawyer) {
var index = $scope.userInfo.lawyers.map(function(e) { return e.id; }).indexOf(lawyer.id);
$scope.userInfo.lawyers.splice(index, 1);
console.log($scope.userInfo.lawyers);
$window.location.href = '#/lawyer';
};
And also, the controller changes will by default be detected by the digest loop of angular so no need to use $scope.$apply.
Also, simplifyed your plunker with the basic get array list and remove function. Use that to build your way forvered
https://plnkr.co/edit/w6NuVLcqzc5Rjs7L6Cox?p=preview

How to get the indexpath or particular id from single list view cell on button click

I have list of items that i am displaying from db. So in each cell i have one button . So each cell have one seperate number ID .So when ever i press any cell button.That particular cell number id i need to get .Just to put one alert or console message to get that particular number ID. How to do that.
For example :
<ion-item ng-repeat="colls in Mycolls | filter: search | limitTo: listlength">
<div>
<img src="img/Reminder.png">
<span>Get number</span>
</div>
<div>
<img src="img/phone.png">
<span>GET NAME</span>
</div>
</ion-item>
This above code is my list view to populate my data, with each cell have one button.Please help me out how can i do that using ng-click.
Here my controller:
.controller('collectionsCtrl', function($scope, $state, $window, $ionicPopup, $stateParams, $ionicLoading, $timeout, $ionicHistory, collectionsfactory) {
$scope.GoBack = function() {
$state.go('menu.mydata');
};
$scope.mdID = "1";
$scope.orderInfo = {
mdID: $scope.mdID
};
$ionicLoading.show();
collectionsfactory.save($scope.orderInfo, function(response) {
if (response.status == 1) {
$ionicLoading.hide();
$scope.Mycolls = response.allcollections;
$window.localStorage.setItem("order", JSON.stringify($scope.Mycolls));
console.log($scope.Mycolls);
} else {
$ionicLoading.hide();
$ionicPopup.alert({
title: "Failed",
content: "<center>" + response.message + "</center>"
});
}
});
});
Add a ng-click to the span in the repeated element that call your functions:
<ion-item ng-repeat="colls in Mycolls" ng-click="getColls(colls)>
<span ng-click="getNumber(colls)">Get number</span>
<span ng-click="getName(colls)">Get name</span>
</ion-item>
Here are getNumber() and getName() functions in controller:
$scope.savedColls = {};
$scope.getNumber = function(colls) {
$scope.savedColls.number = colls.number;
}
$scope.getName = function(colls) {
$scope.savedColls.name = colls.name;
}
call a function by ng-click and pass the id
In html
<span ng-click="getName(colls.name)"></span>
<span ng-click="getNumber(colls.number)"></span>
Inside the controller
$scope.getName = function(name) {
console.log('cell name',name);
}
$scope.getNumber = function(number) {
console.log('cell number',number);
}

append html to the div with AngularJS

How can i pass html through in AngularJS controller ?
Here is my list.html:
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" class="col-md-12 listing-div hidden"></div>
in controller.js:
$scope.pData = [];
$scope.getPackageInfo = function(id,name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function(data) {
if(data != 0) {
$("#lp").html(summery); // this is used to append the data
document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$('#loading').hide();
} else {
document.getElementById("lp").classList.add("hidden");
document.getElementById("np").classList.remove("hidden");
$('#loading').hide();
}
});
};
Here, I have wrote $("#lp").html(summery);, in that div I have to append html which comes from var summery = SubscriptionoptioncompanylistFactory.getSummary(id);. But this is not going to append the data. In console I can see that data comes in summary variable. How can I do?
have a look at below modifications
Use angular ng-show for showing/hiding elements
Use data binding and avoid Jquery like Dom manipulation
<div class="col-xs-3" ng-repeat="item in companyData">
<a ng-click="getPackageInfo({{item.iCompanyID}},'{{item.vCompanyName}}')" class="block panel padder-v bg-primary item">
<span class="text-white block">{{item.vCompanyName}}</span>
</a>
<div id="packagehtml"></div>
</div>
<div id="lp" ng-show="lbVisible" class="col-md-12 listing-div hidden">{{summaryBinding}}</div>
and the controller would look like :
$scope.pData = [];
$scope.getPackageInfo = function (id, name) {
$scope.name = name;
var summery = SubscriptionoptioncompanylistFactory.getSummary(id);
$scope.lbVisible = true; //document.getElementById("lp").classList.remove("hidden");
$('.packages-data').html('');
$scope.loadingVisible = true; //$('#loading').show();
SubscriptionoptioncompanylistFactory.getPackageInDetail(id).
success(function (data) {
if (data != 0) {
$scope.summaryBinding = summery; // $("#lp").html(summery); // this is used to append the data
$scope.npVisible = false; // document.getElementById("np").classList.add("hidden");
Array.prototype.push.apply($scope.pData, data);
$scope.loadingVisible = false; // $('#loading').hide();
} else {
$scope.lbVisible = false; //document.getElementById("lp").classList.add("hidden");
$scope.npVisible = false; //document.getElementById("np").classList.remove("hidden");
$scope.loadingVisible = false; // $('#loading').hide();
}
});
};
your snippet is not showing elements that you use :
np, #loading so just find them and add the `ng-show` with the proper scope variable : `npVisible , lbVisible , loadingVisible`
and note that we add the data using summaryBinding
hope this helps :)

I am calling a function on ng-keyup to search in database and after getting the result i am showing the result in a DIV..?

but when the input search is empty then also it is showing the result but I dont want the result to show when Input Search is Empty
here is my
Services:--
angular.module('a2BClientApp')
.service('AdminSearchService', ['$q', '$http', '$rootScope',
function ($q, $http, $rootScope,$cookies) {
var baseUrl = window.location.origin;
this.searchUser = function(authToken, data){
var deferred = $q.defer();
$http.post(baseUrl+'/api/v1/admin/users',
{searchString: data},
{headers: { 'Authorization': 'Bearer '+ authToken }})
.success(function (response) {
deferred.resolve(response);
$rootScope.user = response;
})
.error(function(err){
deferred.reject(err);
})
return deferred.promise;
}
}]);
and my controller is:
.controller('adminSearchCtrl', function ($scope, $rootScope, $location, AdminSearchService, $cookies){
// $rootScope.user = JSON.parse($cookies.get('AtoB')).user;
var userToken = JSON.parse($cookies.get('AtoB')).user;
$scope.searchUser = function(){
AdminSearchService.searchUser(userToken.token, $scope.userSearchData.searchByUser)
.then(function(response){
$scope.resppppp = response.results;
})
.catch(function(err){
$scope.error = err.message;
});
}
});
and my Html File where I am Showing the Details from server is
<div class="col-md-12 col-sm-12 col-xs-12 userSearchBar" ng-hide="showme">
<div class="search">
<span class="glyphicon glyphicon-search search_icon"></span>
<input class="query" placeholder="Search By User" name="searchByUser" ng-model="userSearchData.searchByUser" id="inputSearch" ng-keyup="searchUser()" />
</div>
<div ng-show="resppppp.length > 0">
<ul ng-repeat="rep in resppppp"><li>{{rep.email}}</li></ul>
</div>
<div ng-show="resppppp.length == 0">NO Result</div>
</div>
Please Help Me Out How to do that.I have added Screen Shot also for UnderStanding I am getting the result even search bar is empty
I got answer for the above question just simply check that input box is empty or not accordingly SHOW and HIDE your DIV
I have put condition in my controller like this inside function after this line
$scope.searchUser = function(){
if(inputSearch.value==0){
$("#dataFetchedFromServer").hide();
}
else{
$("#dataFetchedFromServer").show();
}
}
the id dataFetchedFromServer is given to this DIV
<div ng-show="resppppp.length > 0" id="dataFetchedFromServer"></div>

Angular - Fill dropdown based on selection

HTML
<div class="col-xs-2 type-image" ng-repeat='group in groups'>
<a class="thumbnail" ng-click='selectItem(group)'>
<img src="<% group.image %>" class="img-responsive">
</a>
</div>
<div class="col-md-5 type-description" ng-bind-html="selectedItem.description | unsafe"></div>
<div class="col-md-6 no-gutter">
<select ng-options="gurte.id for gurte in group.gurte"></select>
</div>
app.js
app.controller('gurtController', function($scope, $http) {
$scope.groups = [];
$scope.loading = false;
$scope.init = function() {
$scope.loading = true;
$http.get('/api/groups').
success(function(data, status, headers, config) {
$scope.groups = data;
$scope.loading = false;
});
}
$scope.selectItem = function(item) {
$scope.selectedItem = item;
}
$scope.init();
});
How can I fill the select dropdown based on the selection in the upper block of the HTML? Am I right, that the scope is still on "group" when I have selected it in the top or do I have to pass "group" to the select field somehow?
If needed I can provide the output from the API too. basically its:
Group
-id
-name
-gurte (relationship) ->
- id
- spalten (many to many; ) ->
- id
- name (this needs to go to the dropdown)
-> pivot -> spalten_value

Categories

Resources