List not updating new object in angularjs? - javascript

I am pushing a new object in the array but couldn't see the new value updated on UI. I am using angular js here and updating a value. here is my code.
html
<ul id="list-wrapper-noti" class="dropdown-menu dropdown-menu-right style-3" >
<div infinite-scroll-disabled = "disableScroll" infinite-scroll='loadMoreNotifications()' infinite-scroll-distance='0' infinite-scroll-container="'#list-wrapper-noti'">
<li >
See all
<a class="pull-right" href="list.php?id=20" style=" color:#3C71C1;">Mark all as read </a>
</li>
<li style="height: 30px"></li>
<li ng-repeat = "notification in notifications track by $index">
<a style="text-decoration:none; color:#534D4D" href="{{notification.href}}" >
<div class="media">
<img src="https://papa.fit/routes/images/inst_logo/default.png" alt="fakeimg" class="img-circle pull-left" style="height:50px; width:50px;">
<div class="media-body">
<div class="media">{{notification.employee}} {{notification.action | lowercase}} {{notification.element}} {{notification.record_value}}</div>
<span class="muted">{{notification.time_string}}</span>
</div>
</div>
</a>
<div class="divider"></div>
</li>
controller
function addNewNotification(new_noti){
var obj = {"action":new_noti.data.action,"element":new_noti.data.element,"record_value":new_noti.data.record_value,"time_string":new_noti.data.time_string,"employee":new_noti.data.employee};
$scope.notifications.unshift(obj);
console.log($scope.notifications)
}
and from here I am calling this func
angular.element('#list-wrapper-noti').scope().addNewNotification(payload);
I don't know why it is not getting updated after push in array.please anyone help ?

Inject $timeout into your controller and try this:
$timeout(function() {
$scope.notifications.unshift(obj);
});

Related

jPlayer Cannot read property 'poster' of undefined

I have a problem with jplayer what I need to do is I want to play next track automatically when prev track is finished.
I have HTML as:
<div class="row-track active" data-track-id="30">
<div class="row-holder" data-src="url/30">
<span class="status">
<a href="javascript:;" data-toggle="tooltip" title="" class="play-pause no-pjax addTrack audio-element" data-audio="mp3_url" data-waveform="img_url" data-id="30" data-album-id="74" data-title="Usually Suspect" data-artist="Ambient Drama" data-original-title="#7">play/pause
</a>
</span>
</div>
</div>
<div class="row-track active" data-track-id="40">
<div class="row-holder" data-src="url/40">
<span class="status">
<a href="javascript:;" data-toggle="tooltip" title="" class="play-pause no-pjax addTrack audio-element" data-audio="mp3_url" data-waveform="img_url" data-id="40" data-album-id="74" data-title="Usually Suspect" data-artist="Ambient Drama" data-original-title="#7">play/pause
</a>
</span>
</div>
</div>
And in jplayer -> bind($.jPlayer.event.ended
I have done:
var nextSongId = $("div[data-track-id='"+event.jPlayer.status.media.trackId+"']").
next().attr('data-track-id');
var trackOnEnd = inPlaylist(nextSongId);
demo.play(trackOnEnd);
in demo.playlist I have an array of object.
inPlaylist function is as follows:
function inPlaylist(id) {
var state = null;
$.map(demo.playlist, function(elementOfArray, indexInArray) {
if(elementOfArray.trackId == id) {
state = indexInArray
}
});
return state
};
where status is nothing but the index of the object in an array of object.
In some places it working fine. But in some cases it gives me an error of
Cannot read property 'poster' of undefined

Context Menu not working in ANGULARJS

I am trying to add context menu but value is not populating.
<div class="m-l">
<a class="item-country text-orange" href="#/app/CountryIps/{{item.data['name']}}/cCode/{{item.data['country-code']}}" target="_blank">
{{item['data']['name']}}
</a>
<a class="item-ip" href="#/app/showIps/{{item.data['name']}}/ip/{{item.data['Ip']}}" target="_blank"><span context-menu="whiteList"> {{item.data['Ip']}}</span> </a>
{{item.data['type']}}
<a class="detail-icon" data-popup-open="popup-1" href="" ng-click="showModal(item)">
<i class="fa fa-info-circle"></i>
</a>
</div>
Javascript
$scope.whiteList = [
['Add to white list', function($itemScope, $event, ip) {
whiteList(ip);
}]
];
Now when I add context from template I got undefined in ip in controller.
<a onClick="window.location.href='your link'">
I fixed it by myself to checking values of the $itemscope.
$itemScope.$parent.item.data.Ip
To get the value of the IP from template to controllers.

How do I bind html inside ng-repeat?

How do I dynamically bind the response data to the html generated inside ng-repeat?
Currently, only socialCount is being bound for all li's.
Here's my html:
<li ng-repeat="category in inbox.categories track by $index">
<a href="#">
<div class="left-row" ng-click="inbox.showView(category)" target="_self">
<div class="leftcolumn1"><span class="glyphicon glyphicon-user"></span></div>
<div class="leftcolumn2">{{category}}</div>
<div class="leftcolumn3 email-time" ng-bind="inbox.messageCounts.socialCount"></div>
</div>
</a>
</li>
and the response I get from the server is this:
{"socialCount":431,"promotionsCount":17843,"updatesCount":26997,"forumsCount":1780}
The js function:
Inbox.prototype.getMessageCounts = function(categories){
$http.get(
this.messageCountUrl + this.userGuid).success(function(data){
this.messageCounts=data;
}.bind(this));
Found the answer, just have to do this.
<div class="leftcolumn3 email-time" ng-bind="inbox.messageCounts.{{category|lowercase}}Count"></div>

AngularJS : call a Controller method with ng-click [duplicate]

I have a simple loop with ng-repeat like this:
<li ng-repeat='task in tasks'>
<p> {{task.name}}
<button ng-click="removeTask({{task.id}})">remove</button>
</li>
There is a function in the controller $scope.removeTask(taskID).
As far as I know Angular will first render the view and replace interpolated {{task.id}} with a number, and then, on click event, will evaluate ng-click string.
In this case ng-click gets totally what is expected, ie: ng-click="removeTask(5)". However... it's not doing anything.
Of course I can write a code to get task.id from the $tasks array or even the DOM, but this does not seem like the Angular way.
So, how can one add dynamic content to ng-click directive inside a ng-repeat loop?
Instead of
<button ng-click="removeTask({{task.id}})">remove</button>
do this:
<button ng-click="removeTask(task.id)">remove</button>
Please see this fiddle:
http://jsfiddle.net/JSWorld/Hp4W7/34/
One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:
<button ng-click="removeTask(1234)">remove</button>
I saw:
<button ng-click="removeTask(task.id)">remove</button>
However, the latter works!
This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.
Further, if you wanted to pass the task object itself, you can like:
<button ng-click="removeTask(task)">remove</button>
Also worth noting, for people who find this in their searches, is this...
<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
<div class="bb-button-label">{{ button.label }}</div>
<div class="bb-button-description">{{ button.description }}</div>
</div>
Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
Above answers are excellent. You can look at the following full code example so that you could exactly know how to use
var app = angular.module('hyperCrudApp', []);
app.controller('usersCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users").then(function (response) {
console.log(response.data)
$scope.users = response.data;
$scope.setKey = function (userId){
alert(userId)
if(localStorage){
localStorage.setItem("userId", userId)
} else {
alert("No support of localStorage")
return
}
}//function closed
});
});
#header{
color: green;
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>HyperCrud</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body>
<!-- NAVBAR STARTS -->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">HyperCrud</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
<li class="dropdown">
Apps<span class="caret"></span>
<ul class="dropdown-menu">
<li>qAlarm »</li>
<li>YtEdit »</li>
<li>GWeather »</li>
<li role="separator" class="divider"></li>
<li>WadStore »</li>
<li>chatsAll</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>Register</li>
<li>Services<span class="sr-only">(current)</span></li>
</ul>
</div>
</div>
</nav>
<!--NAVBAR ENDS-->
<br>
<br>
<div ng-app="hyperCrudApp" ng-controller="usersCtrl" class="container">
<div class="row">
<div class="col-sm-12 col-md-12">
<center>
<h1 id="header"> Users </h1>
</center>
</div>
</div>
<div class="row" >
<!--ITERATING USERS LIST-->
<div class="col-sm-6 col-md-4" ng-repeat="user in users">
<div class="thumbnail">
<center>
<img src="https://cdn2.iconfinder.com/data/icons/users-2/512/User_1-512.png" alt="Image - {{user.name}}" class="img-responsive img-circle" style="width: 100px">
<hr>
</center>
<div class="caption">
<center>
<h3>{{user.name}}</h3>
<p>{{user.email}}</p>
<p>+91 {{user.phone}}</p>
<p>{{user.address.city}}</p>
</center>
</div>
<div class="caption">
DELETE
UPDATE
</div>
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a href="/regiser/">
<img src="http://img.bhs4.com/b7/b/b7b76402439268b532e3429b3f1d1db0b28651d5_large.jpg" alt="Register Image" class="img-responsive img-circle" style="width: 100%">
</a>
</div>
</div>
</div>
<!--ROW ENDS-->
</div>
</body>
</html>
HTML:
<div ng-repeat="scannedDevice in ScanResult">
<!--GridStarts-->
<div >
<img ng-src={{'./assets/img/PlaceHolder/Test.png'}}
<!--Pass Param-->
ng-click="connectDevice(scannedDevice.id)"
altSrc="{{'./assets/img/PlaceHolder/user_place_holder.png'}}"
onerror="this.src = $(this).attr('altSrc')">
</div>
</div>
Java Script:
//Global Variables
var ANGULAR_APP = angular.module('TestApp',[]);
ANGULAR_APP .controller('TestCtrl',['$scope', function($scope) {
//Variables
$scope.ScanResult = [];
//Pass Parameter
$scope.connectDevice = function(deviceID) {
alert("Connecting : "+deviceID );
};
}]);
Here is the ng repeat with ng click function and to append with slider
<script>
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
$scope.employees = [
{ 'id': '001', 'name': 'Alpha', 'joinDate': '05/17/2015', 'age': 37 },
{ 'id': '002', 'name': 'Bravo', 'joinDate': '03/25/2016', 'age': 27 },
{ 'id': '003', 'name': 'Charlie', 'joinDate': '09/11/2015', 'age': 29 },
{ 'id': '004', 'name': 'Delta', 'joinDate': '09/11/2015', 'age': 19 },
{ 'id': '005', 'name': 'Echo', 'joinDate': '03/09/2014', 'age': 32 }
]
//This will hide the DIV by default.
$scope.IsVisible = false;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.IsVisible ? false : true;
}
});
</script>
</head>
<body>
<div class="container" ng-app="MyApp" ng-controller="MyController">
<input type="checkbox" value="checkbox1" ng-click="ShowHide()" /> checkbox1
<div id="mixedSlider">
<div class="MS-content">
<div class="item" ng-repeat="emps in employees" ng-show = "IsVisible">
<div class="subitem">
<p>{{emps.id}}</p>
<p>{{emps.name}}</p>
<p>{{emps.age}}</p>
</div>
</div>
</div>
<div class="MS-controls">
<button class="MS-left"><i class="fa fa-angle-left" aria-hidden="true"></i></button>
<button class="MS-right"><i class="fa fa-angle-right" aria-hidden="true"></i></button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="js/multislider.js"></script>
<script>
$('#mixedSlider').multislider({
duration: 750,
interval: false
});
</script>

How to do a foreach binding using KnockoutJS in Bootstrap-themed dropdown

I'm developing a small notifications-like module, where the user can see his 5 latest activities that are logged in the DB (MSSQL). The values that I need are all there, but for some reason knockout binding is not working. Here are code snippets:
<div class="dropdown-menu toolbar pull-right" data-bind="with: layoutLogsModel">
<h3 style="border: none;">Recent activities:</h3>
<!-- "mailbox-slimscroll-js" identifier is used with Slimscroll.js plugin -->
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: layoutLogsModel.notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-book" style="color: orange;"></i>
Some text
</a>
<br>
Some text #2
</div>
</ul>
</div>
For now, I only want to display random text for every item that is in the observableArray.
ViewModel is the following:
var layoutLogsModel = {
notification: ko.observableArray()
};
function getLastFiveActivities() {
get(apiUrl + "Logs/GetLastFiveActivities", { ClientUserID: loggedUserID }, function (data) {
layoutLogsModel.notification(data);
});
}
And every time I call this function, the list is empty (IMAGE)
(the function is called on click, and absolutely no errors are shown in the console).
What is it that I am doing wrong?
EDIT:
The thing was, I forgot to execute ko.applyBindings for that viewModel. Then, I changed the HTML to look like this:
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-user" style="color: green;"></i>
<span data-bind="text: $data"></span>
</a>
</div>
</ul>
Aslo, I modified the get function slightly, like this:
function getLastFiveActivities() {
get(apiUrl + "Logs/GetLastFiveActivities", { ClientUserID: loggedUserID }, function (data) {
layoutLogsModel.notification(data.Notification);
});
}
(changed data to data.Notification based on the MVC model property that contains the array)
After all that, the data was available immediately.
try removing the layoutLogsModel from the foreach, you are already using it with the binding "with", so eveything in that div will be part of layoutLogsModel.
<div class="dropdown-menu toolbar pull-right" data-bind="with: layoutLogsModel">
<h3 style="border: none;">Recent activities:</h3>
<!-- "mailbox-slimscroll-js" identifier is used with Slimscroll.js plugin -->
<ul id="mailbox-slimscroll-js" class="mailbox" data-bind="foreach: notification">
<div class="alert inbox">
<a href="javascript:void(0)">
<i class="icon-book" style="color: orange;"></i>
Some text
</a>
<br>
Some text #2
</div>
</ul>
</div>

Categories

Resources