Angular doesn't retrieve updated_at in laravel - angularjs

i'm trying to retrieve the updated_at time but it gets the created_at time instead even when i passed it in the angular scope function
and renders the incorrect date on created_at after the update has been made
My console reads when updated
1 second ago
so it works but its not getting passed in the view correctly.
PostController
public function update(Post $post)
{
//
$data = request()->validate([
'body' => 'required|string'
]);
$this->authorize('update', $post);
$post->update($data);
$data['id'] = $post->id;
$data['updatedAt'] = $post->updated_at->diffForHumans();
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
public function getPosts()
{
$posts = Post::with('user')
->with(['likes' => function ($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}])
->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
$data = $posts->map(function(Post $post)
{
$user = auth()->user();
if($user->can('delete', $post)) {
$post['deletable'] = true;
}
if($user->can('update', $post)) {
$post['update'] = true;
}
$post['likedByMe'] = $post->likes->count() == 0 ? false : true;
$post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
$post['createdAt'] = $post->created_at->diffForHumans();
$data['updatedAt'] = $post->updated_at->diffForHumans();
return $post;
});
return response()->json($data);
}
main.js
$scope.updatePost = function(post){
$http.post('/auth/upost/' + post.id, {
body: post.body,
updatedAt:post.updatedAt
}).then(function(result, status, headers, config){
$scope.updatedAt = result.data.updatedAt;
console.log($scope.updatedAt);
$scope.myposts.push($scope.updatedAt);
});
};
html
<div id="mypost" class="col-md-8 panel-default animated zoomIn" ng-repeat="post in myposts ">
<div id="eli-style-heading" class="panel-heading"><% post.user.name %></div>
<div class="panel-body panel" ng-init="getLikeText(post); getLikecount(post)">
<i style="color:tomato; float:right; font-size:24px;" ng-click="like(post); toggle = !toggle"
ng-class="{[noheart] : !post.likedByMe, [heart]: post.likedByMe }">
<h3 style="font-size:20px; margin:20px 0px; text-align:center;" ng-bind="post.likesCount"> </h3>
</i>
<figure>
<p class="mybody" ng-model="post.body" editable-text="post.body" e-form="textBtnForm"> <% post.body %></p>
<p name="post.created_at" > <% post.createdAt %> <% post.updatedAt %> </p>
</figure>
<span>
<i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)" ng-if="post.deletable"></i>
<button ng-if="post.update" class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">
Edit
</button>
<span><button ng-if="post.update" type="submit" class="btn btn-primary" ng-click="updatePost(post)">Update</button></span>
</span>
</div>
</div>

this is the correct code my bad for this silly question guys.
public function getPosts()
{
$posts = Post::with('user')
->with(['likes' => function ($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}])
->get();
$response = new Response(json_encode($posts));
$response->headers->set('Content-Type', 'application/json');
$data = $posts->map(function(Post $post)
{
$user = auth()->user();
if($user->can('delete', $post)) {
$post['deletable'] = true;
}
if($user->can('update', $post)) {
$post['update'] = true;
}
$post['likedByMe'] = $post->likes->count() == 0 ? false : true;
$post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
$post['createdAt'] = $post->created_at->diffForHumans();
// $data['updatedAt'] = $post->updated_at->diffForHumans();
//calling again if the post has been updated
$post['createdAt'] = $post->updated_at->diffForHumans();
return $post;
});
return response()->json($data);
}
main.js
remove this its useless and renders out a box
$scope.myposts.push($scope.updatedAt);
html
<% post.createdAt %> is all you need it will render both the created time and updated time

Related

Firebase Call to the dynamic Reference not giving proper output

i am creating a chat application for the browser using angular 1 and ionic 1
here is my controller and view for that
the problem is when the new message comes in the selected room which is current room watch variable and below console giving me proper output but that same method getting called twice giving me proper output at fist call but after that he gives me main node output.
$scope.firstLoad='';
$scope.directLoad='';
$scope.text = "Tap on name to open chat !";
$scope.myUid = localStorage.uid;
$scope.rooms = [];
$scope.roomsfound = 0;
$scope.roomswait = 1;
$scope.name = "";
$scope.number = "";
$scope.currentRoomId="";
$scope.is_select_user = 0;
$scope.loadDetails = function (roomId, contactName, phone, name) {
$timeout(function () {
$scope.firstLoad=false;
},2000);
$rootScope.showLoading("loadchat");
$scope.currentRoomId="";
$scope.name = "";
$scope.number = "";
$scope.name = name;
$scope.number = phone[0] == '1' ? phone.slice(1) : phone;/*to stipe out 1 from the phone number in view*/
$scope.is_select_user = 1;
$scope.roomName = "Chat";
$scope.chats = [];
$scope.chats.length = 0;
$scope.roomId = '';
$scope.roomId = roomId;
$scope.roomName = contactName;
firebase.database().ref('messages/' + $scope.roomId).once('value', function (data) {
$timeout(function () {
var tempArr = [];
data.forEach(function (data) {
tempArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = tempArr;
});
});
$scope.currentRoomId= $scope.roomId;
console.log("In Load Details "+$scope.currentRoomId);
if($scope.firstLoad == false){
firebase.database().ref('rooms/' + $scope.myUid +'/'+$scope.roomId ).update({
isRead:'true'
})
}
$scope.Scroll_top();
$rootScope.hideLoading("loadchat");
}
/*Live Chat Listner for Current Room*/
$scope.$watch(
"currentRoomId",
function handleMessageChange( newValue, oldValue ) {
$timeout(function () {
firebase.database().ref('messages/'+$scope.currentRoomId+'/').on('value', function (data) {
console.log('messages/'+$scope.currentRoomId);
if($scope.currentRoomId != ""){
var liveChatArr = [];
$scope.chats = [];
data.forEach(function (data) {
liveChatArr.push({
key: data.key,
content: data.val().message,
createdAt: data.val().timestamp,
from: data.val().sendBy,
to: data.val().sentTo,
direction: data.val().direction,
status: data.val().status,
type: data.val().type
})
});
$scope.chats = [];
$scope.chats.length=0;
if( $scope.chats.length == 0)
$scope.chats=liveChatArr ;
else{
$scope.chats = [];
$scope.chats.length=0;
$scope.chats=liveChatArr ;
}
$scope.Scroll_top();
}
});
},3000);
});
/*End Live Chat Listener*/
/*Send New Message*/
$scope.data = {};
$scope.sendMessage = function (roomId, message, name, phone, contactName) {
Chats.send(roomId, $scope.myUid, message);
document.getElementById("mymsg").value = "";
$scope.data.message='';
};
/* End Send New Message*/
/* Live Room Listner*/
firebase.database().ref('rooms/' + $scope.myUid).orderByChild('lastMessageAt').on('value', function (data) {
$scope.liverooms = [];
$scope.liverooms.length = 0;
$scope.rooms = [];
$scope.rooms.length=0;
$timeout(function () {
var unique = function(origArr) {
//console.log(origArr);
var newArr = [];
var origLen = origArr.length;
var found, x, y;
for (x = 0; x < origLen; x++) {
//console.log(x);
found = undefined;
for (y = 0; y < newArr.length; y++) {
if (origArr[x] === newArr[y]) {
found = true;
break;
}
}
if (!found) {
newArr.push(origArr[x]);
}
}
return newArr;
}
data.forEach(function (data) {
var ref=firebase.database().ref('rooms/' + $scope.myUid);
var key = data.ref.key;
var fields = key.split('_');
var len = fields.length;
var mobile = fields[len - 1];
$scope.liverooms.push({
roomId: key,
contactName: data.val().contactName,
contactfName: (data.val().contactName.split(' '))[0],
lastMessage: data.val().lastMessage,
lastMessageAt: data.val().lastMessageAt,
lastMessageDirection: data.val().lastMessageDirection,
phone: mobile[0] == '1' ? mobile.slice(1) : mobile,
isRead:data.val().isRead
});
});
$scope.rooms = [];
$scope.rooms.length=0;
if( $scope.rooms.length == 0 ){
$scope.rooms=unique($scope.liverooms).reverse();
}else{
$scope.rooms = [];
$scope.rooms.length=0;
$scope.rooms=unique($scope.liverooms).reverse();
}
//console.log($scope.rooms);
});
$scope.roomswait = 0;
if ($scope.rooms.length > 0) {
$scope.roomsfound = 1;
}
});
/* End Live Room Listner*/
VIEW
<div class="content-wrapper">
<div class="container-fluid">
<div class="col-lg-3 searchmain-box">
<br>
<div class="input-group col-sm-6 col-xs-3 col-md-12 mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon radius-left search-box"><i class="fa fa-search"></i></div>
<input type="text" class="form-control radius-right search-box" ng-model="search" id="inlineFormInputGroup" placeholder="Search">
</div>
<br>
<div class="col-md-12 text-center" ng-show="roomswait == 1">
<img src="img/loading.gif" width="30">
<br>
<h5 class="text-white">Please Wait.. Loading Chats</h5>
</div>
<ul class="list-group user-list" ng-show="roomsfound == 0">
<li class="list-group-item user-list" style="cursor:pointer;outline:none" ng-if="room" ng-repeat="room in rooms| filter:search " ng-init="($first && firstLoad) ? loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName) : ''" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">
<!--<li class="list-group-item user-list" ng-repeat="room in rooms| orderBy:'lastMessageAt':true | filter:search" type="item-text-wrap" ng-click="loadDetails(room.roomId, room.contactName + ' (' + room.phone + ')', room.phone, room.contactName)">-->
<div class="user-profile" ng-if="room.contactName == name && room.phone == number">
<span><img src="img/liveicon.png"></span>
</div>
<div class="user-name" >
<h4 class="ma-0" ng-class="{'user-live':room.contactName == name && room.phone == number , 'dark-text':(room.contactName != name || room.phone != number) && room.isRead != 'false' , 'not_read':room.isRead == 'false'}" >
{{room.contactName}}
<span class="live-chaticon"></span>
</h4>
<span style="float:left"><img src="img/phone.png"/></span>
<p class="user-phoneno mb-0" style="padding:5px;margin-left: 16px;" ng-class="{'not_read':room.isRead == 'false'}">
{{room.phone| bcTelephone:'format'}}
</p>
<p class="user-message mb-0" style="font-size: 12px;" ng-show="room.lastMsg != ''" ng-class="{'not_read':room.isRead == 'false', 'dark-text':room.isRead == 'true'}">
<span ng-if="room.lastMessageDirection == 'out'">You:</span>
<span ng-if="room.lastMessageDirection == 'in'">{{room.contactfName}}:</span>
{{(room.lastMessage| limitTo: 20) + (room.lastMessage.length > 20 ? '..' : '')}}
</p>
</div>
<div class="user-time">
<p class="dark-text">
<span class="time2" ng-show="room.lastMessageAt != ''" am-time-ago="room.lastMessageAt"></span>
</p>
</div>
</li>
</ul>
</div>
<div class="recent-bg" block-ui="loadchat" style="width:61%;position:fixed;top:0;right:0;background-color:white">
<div class="recent-order">
<!-- <div class="recent-text ">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>-->
<div class="recent-text ">
<div class="row">
<div class="col-md-3">
<h4 class="user-name">{{name}} <span class="live-chaticon"></span></h4>
<!--<h5 class="user-number">{{number}} </h5>-->
<!--<h5 class="user-number"> {{number| bcTelephone:'format'}} </h5>-->
<h5> <span style="float:left"><img src="img/phone.png" height="20px"/></span> {{number| bcTelephone:'format'}} </h5>
</div>
</div>
</div>
</div>
<div class="col-12 pa-0">
<h5 ng-if="text != ''" class="text-center">{{text}}</h5>
<div class="table-responsive">
<div class="frame">
<div ng-show="chats.length != 0">
<ul class="message-box">
<li ng-repeat="chat in chats| orderBy:'createdAt':false" ng-if="chat" ng-class="{'pull-right default-user ': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}">
<p>{{chat.content}} <br>
<span style="font-size: 10px;" am-time-ago="chat.createdAt" ng-class="{'pull-right default-user': chat.direction == 'out','pull-left client-user':chat.direction != 'out'}"></span>
<br>
<span style="font-size: 10px; float: right" > {{chat.status}}</span>
</p>
</li>
</ul>
</div>
<div class="message-sendbtn" style="position:fixed;width:61%" ng-show="is_select_user">
<div class="input-group">
<input type="text" class="form-control message-control" id="mymsg" placeholder="Your message" ng-model="data.message" aria-label="Recipient's username" aria-describedby="basic-addon2" ng-enter="sendMessage(roomId, data.message, name, number, roomName)">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is My View
I am getting issue when new message comes in node Contact list which is Room array getting double records and when i send message some time its not showing live status of message and some time it messes up with wrong node (Current Room)
By using on("value") method is getting called multiple times.
Kindly help me i am stuck here.

How to use $http service of angularjs to get data from mongodb using node js code

//Here is my angular app now i want to get mongodb data in json using node how to use $http service
<tr ng-repeat="x in ItemsByPage[currentPage] | orderBy:columnToOrder:reverse">
<td >{{x.id}}</td> // how to get data here from a json data of mongodb
<td >
<!-- editable username (text with validation) -->
<span editable-text="x.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, x.id)" e-required>
{{ x.name || 'empty' }}
</span>
</td>
<td>
<!-- editable status (select-local) -->
<span editable-text="x.lName" e-name="lName" e-form="rowform">
{{ x.lName || 'empty' }}
</span>
</td>
<td >
<!-- editable group (select-remote) -->
<span editable-text="x.pages" e-name="pages" e-form="rowform" >
{{ x.pages || 'empty' }}
</span>
</td>
<td>
<span editable-text="x.passw1" e-name="passw1" e-form="rowform" >
{{x.passw1 || 'empty'}}
</span>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" ng-show="rowform.$visible" class="form-buttons form-inline">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeUser($index)">del</button>
</div>
</td>
</tr>
</table>
<button class="btn btn-default" ng-click="addUser()">Add row</button>
<br>
<ul class="pagination pagination-sm">
<li ng-class="{active:0}">First
</li>
<li ng-repeat="n in range(ItemsByPage.length)"> 1
</li>
<li>Last
</li>
</ul>
</div>
<button type="button" onclick="loadDoc(this.value)">Change Content</button>
<!-- <div id="txtHint">Customer info will be listed here...</div> -->
View Records
<script>
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.service('filteredListService', function () {
this.searched = function (valLists,toSearch) {
return _.filter(valLists,
function (i) {
/* Search Text in all 3 fields */
return searchUtil(i, toSearch);
});
};
this.paged = function (valLists,pageSize)
{
retVal = [];
for (var i = 0; i < valLists.length; i++) {
if (i % pageSize === 0) {
retVal[Math.floor(i / pageSize)] = [valLists[i]];
} else {
retVal[Math.floor(i / pageSize)].push(valLists[i]);
}
}
return retVal;
};
});
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', function($scope, $filter, filteredListService) {
$scope.users = [
{id:1, name:'harry potter', lName:"Pege" ,passw1:"12/12/2012",pages:"556"},
{id:2, name:'narnia', lName:"Pim" ,passw1:"12/12/2012",pages:"557"},
{id:3, name:'panchtantra', lName:"Smith" ,passw1:"1/03/2009",pages:"556"},
{id:4, name:'atlas', lName:"Jones" ,passw1:"2/04/1995",pages:"888"},
{id:5, name:'science', lName:"Doe" ,passw1:"2/04/1995",pages:"888"},
{id:6, name:'guiness book',lName:"Pan" ,passw1:"2/04/1995",pages:"888"},
{id:7, name:'panchtantra1', lName:"Smith" ,passw1:"1/03/2009",pages:"556"},
{id:8, name:'atlas1', lName:"Jones" ,passw1:"2/04/1995",pages:"888"},
{id:9, name:'science1', lName:"Doe" ,passw1:"2/04/1995",pages:"888"},
{id:10, name:'guiness book1',lName:"Pan" ,passw1:"2/04/1995",pages:"888"},
];
$scope.checkName = function(data, id) {
if (id === 2 && data !== 'narnia') {
return "Username 2 should be `narnia(case sensitive)`";
}
};
$scope.saveUser = function(data, id) {
//$scope.user not updated yet
angular.extend(data, {id: id});
return $http.post('/saveUser', data);
};
// remove user
$scope.removeUser = function(index) {
var index1 = index + $scope.currentPage * 4;
$scope.users.splice(index1,1);
$scope.pagination();
};
// add user
$scope.addUser = function($event) {
$scope.currentPage = 2;
$scope.id= $scope.users.length + 1
$scope.users.push({
id:this.id,
name:'Enter Book Name',
lName:'Author Name',
passw1:'Date of Publish',
pages:'Pages'
});
$scope.pagination();
alert(users.id);
$scope.resetAll();
}
//search
$scope.pageSize = 4;
$scope.allItems = $scope.users;
$scope.reverse = false;
$scope.resetAll = function () {
$scope.filteredList = $scope.allItems;
$scope.newEmpId = '';
$scope.newName = '';
$scope.newEmail = '';
$scope.searchText = '';
$scope.currentPage = 0;
$scope.Header = ['','',''];
}
//pagination
$scope.pagination = function () {
$scope.ItemsByPage = filteredListService.paged( $scope.filteredList, $scope.pageSize );
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
$scope.firstPage = function () {
$scope.currentPage = 0;
};
$scope.lastPage = function () {
$scope.currentPage = $scope.ItemsByPage.length - 1;
};
$scope.range = function (input, total) {
var ret = [];
if (!total) {
total = input;
input = 0;
}
for (var i = input; i < total; i++) {
if (i != 0 && i != total - 1) {
ret.push(i);
}
}
return ret;
};
$scope.sort = function(sortBy){
$scope.resetAll();
$scope.pagination();
};
$scope.sort ('name');
$scope.search = function () {
$scope.filteredList =
filteredListService.searched($scope.allItems, $scope.searchText);
if ($scope.searchText == '') {
$scope.filteredList = $scope.allItems;
}
$scope.pagination();
}
$scope.resetAll();
});
function searchUtil(x,toSearch)
{
/* Search Text in all 3 fields */
return ( x.name.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.lName.toLowerCase().indexOf(toSearch.toLowerCase()) > -1 || x.id == toSearch
)
? true : false ;
}
</script>
</body>
</html>
//here it is my nodejs file.how to get data from /view-feedbacks in my angularjs .i am a tyro to this.please help me out with $http service only.thereafter how to use ng-repeat to get that data in table.
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("book");
dd.collection('users').find({}).toArray().then(function(feedbacks) {
res.status(200).json(feedbacks);
});
});
});
app.listen(process.env.PORT || 3100, process.env.IP || '0.0.0.0' );
Is your nodejs code is correct.
app.get('/view-feedbacks', function(req, res) {
dbConn.then(function(db) {
var dd=db.db("book"); // not sure of this line, it depends on how you started.
dd.collection('users').find().toArray().then(function(err, feedbacks) { // the first parameter will always be err
console.log("feedbacks",feedbacks);//check whether you are getting feedbacks from your mongodb
res.send(feedbacks); //no need for status here
});
});
});

when ng-repeat list of folders updates wrong

I have receive listof objects with names: F1,F2,F3,F4
when I make call to server, I receive new list F1,F2,F3,F5,F4
when I apdate ng-repeat list:
vm.folders = data.content.items;
it shows next list: F1,F2,F3,F4,F4
where am I wrong? here is my html code:
<div ng-repeat="folder in vm.folders track by $index" ng-init="openInput=false;">
<div layout="row" ng-init="folderName = vm.getIterationName(folder.metadata)" >
<div >
</div>
<div >
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{folderName}}</span>
</div>
</div>
</div>
js update method:
function updateIterations(data) {
if (data.ok === true) {
if(angular.toJson(vm.folders) != angular.toJson(data.content.items)) {
vm.folders = data.content.items;
}
} else if (data.ok == false) {
console.log ('Error:iteration request: {ok: false}');
$interval.cancel(intervalRequests);
}
}
fixed!
in
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{folderName}}</span>
instead of {{folderName}} i've used:
<span ng-click="showChildren[$index]=!showChildren[$index]" class="capitalize" ng-dblclick="openInput = true;$event.stopPropagation();" ng-show="!openInput">{{vm.getIterationName(folder.metadata)}}</span>

ng-repeat with controller for each table row: how do I access x-editable form elements?

I setting up a scenario very similar to the Editable Row example from the x-editable demo site. In this scenario, a there is a simple table with three columns for data and a fourth for edit and delete buttons. A third button outside of the table adds a row to the table. When the form is editable, the data columns become editable (the primary feature of x-editable library). For this demo, the first column becomes a simple text edit and the second two columns become drop lists.
The table is created by having an ng-repeat on a row template. I need to do a few different things that all involve accessing the scope created by the ng-repeat. I need to
detect when the row is editable and when it is not
filter the options for the second drop list when the first drop list changes
In order to try to work with this demo, I've added a controller for the individual row. That has given me some access to the form (name = rowform), but I'm still not able to set a watch on the "make" property. I can't even find what property of the form is changing when the user makes a selection.
How do I set up a watch on the 'make' property?
Page Controller
angular.module('app').controller("quoteBuckingRaterController",
function ($scope, $q, $filter, listService, transactionDataService) {
$scope.equipment = [];
$scope.makes = [];
$scope.models = [];
$scope.showModel = function(equip) {
if(equip.model) {
var selected = $filter('filter')($scope.models, {id: equip.model});
return selected.length ? selected[0].name : 'Not set';
} else {
return 'Not set';
}
};
$scope.showMake = function(equip) {
if (equip.model) {
var selected = $filter('filter')($scope.models, { id: equip.model });
if (selected.length && selected.length > 0) {
if (equip.make != selected[0].make)
equip.make = selected[0].make;
return selected[0].make;
}
else {
return 'Not set';
}
} else {
return 'Not set';
}
};
$scope.checkName = function (data, id) {
if (!data) {
return "Description is required";
}
};
$scope.checkModel = function (data, id) {
if (!data) {
return "Model is required";
}
};
$scope.saveEquipment = function (data, id) {
$scope.inserted = null;
};
$scope.cancelRowEdit = function (data, id) {
$scope.inserted = null;
};
$scope.removeEquipment = function(index) {
$scope.equipment.splice(index, 1);
};
$scope.addEquipment = function() {
$scope.inserted = {
id: $scope.equipment.length+1,
name: '',
make: null,
model: null
};
$scope.equipment.push($scope.inserted);
};
$scope.filterModels = function (make) {
$scope.models = _.where($scope.allModels, function(item) {
return item.make == make;
});
};
//called by another process when page loads
$scope.initialize = function (loaded) {
return $q(function (resolve, reject) {
if (!loaded) {
listService.getEquipmentModels().then(function (data) {
$scope.allModels = data;
$scope.models = data;
//uses underscore.js
$scope.makes = _.chain(data)
.map(function (item) {
var m = {
id: item.make,
name: item.make
};
return m;
})
.uniq()
.value();
resolve();
});
}
});
}
});
Row Controller
angular.module('app').controller("editRowController",
function ($scope) {
$scope.testClick = function () {
alert('button clicked');
};
$scope.make = null;
$scope.$watch('make', function () {
alert('how do I tell when the make has been changed?');
this.$parent.$parent.filterModels(make.id);
});
});
HTML
<div>
<div class="col-md-12" style="margin-bottom: 3px">
<div class="col-md-4 col-md-offset-1" style="padding-top: 6px; padding-left: 0px"><label>Equipment</label></div>
<div class="col-md-offset-10">
<button class="btn btn-primary btn-sm" ng-click="addEquipment()">Add row</button>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<table class="table table-bordered table-hover table-condensed">
<tr style="font-weight: bold; background-color: lightblue">
<td style="width:35%">Name</td>
<td style="width:20%">Make</td>
<td style="width:20%">Model</td>
<td style="width:25%">Edit</td>
</tr>
<tr ng-repeat="equip in equipment" ng-controller="editRowController">
<td>
<!-- editable equip name (text with validation) -->
<span editable-text="equip.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, equip.id)" e-required>
{{ equip.name || 'empty' }}
</span>
</td>
<td>
<!-- editable make (select-local) -->
<span editable-select="equip.make" e-name="make" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
{{ showMake(equip) }}
</span>
</td>
<td>
<!-- editable model (select-remote) -->
<span editable-select="equip.model" e-name="model" e-form="rowform" e-ng-options="g.id as g.name for g in models" onbeforesave="checkModel($data, equip.id)" e-required>
{{ showModel(equip) }}
</span>
<button type="button" ng-disabled="rowform.$waiting" ng-click="testClick()" class="btn btn-default">
test
</button>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" onbeforesave="saveEquipment($data, equip.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == equip">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeEquipment($index)">del</button>
</div>
</td>
</tr>
</table>
</div>
</div>
ng-repeat creates a child scope for each row (for each equipment). The scope of the EditRowController is therefore a childScope of the parent quoteBuckingRaterController.
This childScope contains:
all properties of the parent scope (e.g. equipment, makes, models)
the property equip with one value of the equipment array, provided by ng-repeat
any additional scope property that is defined inside the ng-repeat block, e.g. rowform
Therefore you are able to access these properties in the childController editRowController using the $scope variable, e.g.:
$scope.equip.make
$scope.equipment
and inside the ng-repeat element in the html file by using an angular expression, e.g:
{{equip.make}}
{{equipment}}
Now to $scope.$watch: If you provide a string as the first argument, this is an angular expression like in the html file, just without surrounding brackets {{}}. Example for equip.make:
$scope.$watch('equip.make', function (value) {
console.log('equip.make value (on save): ' + value);
});
However, angular-xeditable updates the value of equip.make only when the user saves the row. If you want to watch the user input live, you have to use the $data property in the rowform object, provided by angular-xeditable:
$scope.$watch('rowform.$data.make', function (value) {
console.log('equip.make value (live): ' + value);
}, true);
You can also use ng-change:
<span editable-select="equip.make" e-name="make" e-ng-change="onMakeValueChange($data)" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
JS:
$scope.onMakeValueChange = function(newValue) {
console.log('equip.make value onChange: ' + newValue);
}
That should solve your first question: How to watch the make property.
Your second question, how to detect when the row is editable and when it is not, can be solved by using the onshow / onhide attributes on the form or by watching the $visible property of the rowform object in the scope as documented in the angular-xeditable reference
<form editable-form name="rowform" onshow="setEditable(true)" onhide="setEditable(false)">
$scope.setEditable = function(value) {
console.log('is editable? ' + value);
};
// or
$scope.$watch('rowform.$visible', function(value) {
console.log('is editable? ' + value);
});
You might ask why the rowform object is in the current childScope.
It is created by the <form> tag. See the Angular Reference about the built-in form directive:
Directive that instantiates FormController.
If the name attribute is specified, the form controller is published
onto the current scope under this name.
A working snippet with your example code:
angular.module('app', ["xeditable"]);
angular.module('app').controller("editRowController", function ($scope) {
$scope.testClick = function () {
alert('button clicked');
};
$scope.$watch('equip.make', function (value) {
console.log('equip.make value (after save): ' + value);
});
$scope.$watch('rowform.$data.make', function (value) {
console.log('equip.make value (live): ' + value);
}, true);
// detect if row is editable by using onshow / onhide on form element
$scope.setEditable = function(value) {
console.log('is equip id ' + $scope.equip.id + ' editable? [using onshow / onhide] ' + value);
};
// detect if row is editable by using a watcher on the form property $visible
$scope.$watch('rowform.$visible', function(value) {
console.log('is equip id ' + $scope.equip.id + ' editable [by watching form property]? ' + value);
});
});
angular.module('app').controller("quoteBuckingRaterController", function ($scope, $filter) {
$scope.equipment = [];
$scope.makes = [{value: 1, name: 'Horst'}, {value: 2, name: 'Fritz'}];
$scope.models = [{id: 1, name: 'PC', make: 1}];
$scope.showModel = function(equip) {
if(equip.model) {
var selected = $filter('filter')($scope.models, {id: equip.model});
return selected.length ? selected[0].name : 'Not set';
} else {
return 'Not set';
}
};
$scope.showMake = function(equip) {
if (equip.model) {
var selected = $filter('filter')($scope.models, { id: equip.model });
if (selected.length && selected.length > 0) {
if (equip.make != selected[0].make)
equip.make = selected[0].make;
return selected[0].make;
}
else {
return 'Not set';
}
} else {
return 'Not set';
}
};
$scope.checkName = function (data, id) {
if (!data) {
return "Description is required";
}
};
$scope.checkModel = function (data, id) {
if (!data) {
return "Model is required";
}
};
$scope.saveEquipment = function (data, id) {
$scope.inserted = null;
};
$scope.cancelRowEdit = function (data, id) {
$scope.inserted = null;
};
$scope.removeEquipment = function(index) {
$scope.equipment.splice(index, 1);
};
$scope.addEquipment = function() {
$scope.inserted = {
id: $scope.equipment.length+1,
name: '',
make: null,
model: null
};
$scope.equipment.push($scope.inserted);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-xeditable/0.1.9/js/xeditable.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/angular-xeditable/0.1.9/css/xeditable.css" rel="stylesheet"/>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div ng-app="app" ng-controller="quoteBuckingRaterController">
<div class="col-md-12" style="margin-bottom: 3px">
<div class="col-md-4 col-md-offset-1" style="padding-top: 6px; padding-left: 0px"><label>Equipment</label></div>
<div class="col-md-offset-10">
<button class="btn btn-primary btn-sm" ng-click="addEquipment()">Add row</button>
</div>
</div>
<div class="col-md-10 col-md-offset-1">
<table class="table table-bordered table-hover table-condensed">
<tr style="font-weight: bold; background-color: lightblue">
<td style="width:35%">Name</td>
<td style="width:20%">Make</td>
<td style="width:20%">Model</td>
<td style="width:25%">Edit</td>
</tr>
<tr ng-repeat="equip in equipment" ng-controller="editRowController">
<td>
<!-- editable equip name (text with validation) -->
<span editable-text="equip.name" e-name="name" e-form="rowform" onbeforesave="checkName($data, equip.id)" e-required>
{{ equip.name || 'empty' }}
</span>
</td>
<td>
<!-- editable make (select-local) -->
<span editable-select="equip.make" e-name="make" e-form="rowform" e-ng-options="s.value as s.name for s in makes">
{{ showMake(equip) }}
</span>
</td>
<td>
<!-- editable model (select-remote) -->
<span editable-select="equip.model" e-name="model" e-form="rowform" e-ng-options="g.id as g.name for g in models" onbeforesave="checkModel($data, equip.id)" e-required>
{{ showModel(equip) }}
</span>
<button type="button" ng-disabled="rowform.$waiting" ng-click="testClick()" class="btn btn-default">
test
</button>
</td>
<td style="white-space: nowrap">
<!-- form -->
<form editable-form name="rowform" onbeforesave="saveEquipment($data, equip.id)" ng-show="rowform.$visible" class="form-buttons form-inline" shown="inserted == equip" onshow="setEditable(true)" onhide="setEditable(false)">
<button type="submit" ng-disabled="rowform.$waiting" class="btn btn-primary">
save
</button>
<button type="button" ng-disabled="rowform.$waiting" ng-click="rowform.$cancel()" class="btn btn-default">
cancel
</button>
</form>
<div class="buttons" ng-show="!rowform.$visible">
<button class="btn btn-primary" ng-click="rowform.$show()">edit</button>
<button class="btn btn-danger" ng-click="removeEquipment($index)">del</button>
</div>
</td>
</tr>
</table>
</div>
</div>
If you simply want to $watch the make property of equipment, try changing to:
$scope.$watch('equipment.make', function(){(...)})
You could write your own directive for this.
The main advantage is that directives have isolated scope and can have their own controller.
see the directive documentation to know if it's for you.

ng-change event not firing inside the loop

function friendControllerTest($scope, $http) {
$scope.loading = true;
$scope.addMode = false;
$scope.countryList = [];
$scope.stateList = [];
function getAllCountry() {
$http({
method: 'Get',
url: '/Home/GetCountry'
}).success(function (data) {
$scope.countryList = data;
}).error(function () {
$scope.errorMessage = 'Not found';
});
}
function getStatebyCountryId(Id) {
$scope.stateList = null;
if (Id) { // Check here country Id is null or not
$http({
method: 'POST',
url: '/Home/GetStateByCountryId/',
data: JSON.stringify({ CountryId:Id })
}).success(function (data) {
$scope.stateList = data;
}).error(function (data) {
alert(data.message);
$scope.message = 'not found';
});
}
else {
$scope.stateList = null;
}
}
$scope.GetStatesList = function (id) {
if (id) { // Check here country Id is null or not
$http({
method: 'POST',
url: '/Home/GetStateByCountryId/',
data: JSON.stringify({ CountryId: id })
}).success(function (data) {
$scope.stateList = data;
}).error(function (data) {
alert(data.message);
$scope.message = 'not found';
});
}
else {
$scope.stateList = null;
}
}
$scope.myMethod = function () {
var text = $scope.newfriend.SearchText;
$http.get('../Home/GetFriendsList', { params: { 'text': text } }).success(function (data) {
$scope.friends = data;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
});
}
$http.get('../Home/GetFriendsList').success(function (data) {
alert("list called")
$scope.friends = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.toggleAdd = function () {
$scope.addMode = !$scope.addMode;
if ($scope.addMode) {
getAllCountry();
}
};
$scope.toggleEdit = function () {
this.friend.editMode = !this.friend.editMode;
getAllCountry();
if (this.friend.Country.Id > 0)
getStatebyCountryId(this.friend.Country.Id);
};
$scope.add = function () {
$scope.loading = true;
var newfriend = {
firstname: $scope.newfriend.firstname,
lastname: $scope.newfriend.lastName,
address: $scope.newfriend.address,
postalcode: $scope.newfriend.PostalCode,
notes: $scope.newfriend.Notes,
CountryId: $scope.newfriend.Country.Id,
StateId: $scope.newfriend.State.Id
}
$http.post('../Home/AddFriends', newfriend).success(function (data) {
alert("Added Successfully!!");
$scope.addMode = false;
$scope.friends.push(data);
$scope.loading = false;
$scope.newfriend = "";
}).error(function (data) {
$scope.error = "An Error has occured while Adding Friend! " + data;
$scope.loading = false;
});
};
$scope.save = function () {
$scope.loading = true;
var frien = this.friend;
$http.put('../Home/EditFriend', frien).success(function (data) {
alert("Saved Successfully!!");
frien.editMode = false;
$scope.loading = false;
}).error(function (data) {
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
$scope.deletefriend = function () {
$scope.loading = true;
var friendid = this.friend.Id;
$http.delete('../Home/RemoveFriend/' + friendid).success(function (data) {
alert("Deleted Successfully!!");
$.each($scope.friends, function (i) {
if ($scope.friends[i].Id === friendid) {
$scope.friends.splice(i, 1);
return false;
}
});
$scope.loading = false;
}).error(function (data) {
$scope.error = "An Error has occured while Saving Friend! " + data;
$scope.loading = false;
});
};
}
<html data-ng-app="" data-ng-controller="friendControllerTest">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="container">
<strong class="error">{{ error }}</strong>
<div id="mydiv" data-ng-show="loading">
<img src="Images/ajax-loader1.gif" class="ajax-loader" />
</div>
<p data-ng-hide="addMode">
<a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New
</a>
</p>
<form name="addFriend" data-ng-show="addMode" style="width: 600px; margin: 0px auto;">
<label>FirstName:</label><input type="text" data-ng-model="newfriend.firstname" required />
<label>LastName:</label><input type="text" data-ng-model="newfriend.lastName" required />
<label>Address:</label><input type="text" data-ng-model="newfriend.address" required />
<label>Country:</label>
<select ng-model="newfriend.Country" ng-options="c.Name for c in countryList track by c.Id" ng-change="GetStatesList(newfriend.Country.Id)">
<option value="">Select Country</option>
</select>
<label>State:</label>
<select ng-model="newfriend.State" ng-options="s.Name for s in stateList track by s.Id">
<option value="">Select State</option>
</select>
<label>PostalCode:</label><input type="text" data-ng-model="newfriend.PostalCode" required />
<label>Notes:</label><input type="text" data-ng-model="newfriend.Notes" required />
<br />
<br />
<input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addFriend.$valid" class="btn btn-primary" />
<input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
<br />
<br />
</form>
<table class="table table-bordered table-hover" style="width: 800px">
<tr>
<th>#</th>
<td>FirstName</td>
<th>LastName</th>
<th>Address</th>
<th>Country</th>
<th>State</th>
<th>PostalCode</th>
<th>Notes</th>
</tr>
<tr data-ng-repeat="friend in friends">
<td><strong>{{ friend.Id }}</strong></td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.firstname}}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.firstname" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.lastname }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.lastname" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.address }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.address" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.Country.Name }}</p>
<select data-ng-show="friend.editMode" ng-model="friend.Country" ng-options="c.Name for c in countryList track by c.Id" ng-change="$parent.GetStatesList(friend.Country.Id)">
<option value="">Select Country</option>
</select>
</td>
<td>
<p data-ng-hide="friend.editMode">{{friend.State.Name }}</p>
<select data-ng-show="friend.editMode" ng-model="friend.State" ng-options="s.Name for s in stateList track by s.Id">
<option value="">Select State</option>
</select>
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.postalcode }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.postalcode" />
</td>
<td>
<p data-ng-hide="friend.editMode">{{ friend.notes }}</p>
<input data-ng-show="friend.editMode" type="text" data-ng-model="friend.notes" />
</td>
<td>
<p data-ng-hide="friend.editMode"><a data-ng-click="toggleEdit(friend)" href="javascript:;">Edit</a> | <a data-ng-click="deletefriend(friend)" href="javascript:;">Delete</a></p>
<p data-ng-show="friend.editMode"><a data-ng-click="save(friend)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(friend)" href="javascript:;">Cancel</a></p>
</td>
</tr>
</table>
<hr />
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/angularjs")
<script src="~/Scripts/MyScript.js"></script>
</body>
I am trying to open my Country and state dropdown in edit mode and so far i am successfull in that.
But the only problem is when i am clicking on any record to open in edit mode my both country and state dropdown are binding correctly but when i am selecting other country from country dropdown then my ng-change is not firing and i dont know why.
This is my view for adding a new record:
<select ng-model="newfriend.Country" ng-options="c.Name for c in countryList track by c.Id" ng-change="GetStatesList()">
<option value="">Select Country</option>
</select>
<label>State:</label>
<select ng-model="newfriend.State" ng-options="s.Name for s in stateList track by s.Id">
<option value="">Select State</option>
</select>
My Controller:
function friendControllerTest($scope, $http) {
$scope.GetStatesList = function () {
//server side call to fetch state by country id
}
$scope.toggleEdit = function () {
this.friend.editMode = !this.friend.editMode;
getAllCountry();
if (this.friend.Country.Id > 0)
getStatebyCountryId(this.friend.Country.Id);
};
};
My Display records view:
<table class="table table-bordered table-hover" style="width: 800px">
<tr data-ng-repeat="friend in friends">
<td>
<p data-ng-hide="friend.editMode">{{ friend.Country.Name }}</p>
<select data-ng-show="friend.editMode" ng-model="friend.Country" ng-options="c.Name for c in countryList track by c.Id" ng-change="GetStatesList()">
<option value="">Select Country</option>
</select>
</td>
<td>
<p data-ng-hide="friend.editMode">{{friend.State.Name }}</p>
<select data-ng-show="friend.editMode" ng-model="friend.State" ng-options="s.Name for s in stateList track by s.Id">
<option value="">Select State</option>
</select>
</td>
</tr>
<table>
public class HomeController : Controller
{
//
// GET: /Home/
private FriendsEntities db = new FriendsEntities();
public ActionResult Index()
{
return View();
}
public ActionResult GetFriendsList(string text)
{
var data = db.Friends.Select
(
d => new FriendModel
{
Id=d.Id,
firstname = d.firstname,
lastname = d.lastname,
address = d.address,
notes = d.notes,
postalcode = d.postalcode,
Country = d.Country.Friends.Select
(
x => new CountryModel
{
Id=x.Country.Id,
Name = x.Country.Name
}
).FirstOrDefault(),
State = d.State.Friends.Select
(
s => new StateModel
{
Id=s.State.Id,
Name = s.State.Name
}
).FirstOrDefault()
}
).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult AddFriends(Friends FriendsModel)
{
var result = db.Friends.Add(FriendsModel);
db.SaveChanges();
var data = db.Friends.Where(t => t.Id == result.Id).Select
(
d => new FriendModel
{
Id=d.Id,
firstname = d.firstname,
lastname = d.lastname,
address = d.address,
notes = d.notes,
postalcode = d.postalcode,
Country = d.Country.Friends.Select
(
x => new CountryModel
{
Id=x.Country.Id,
Name = x.Country.Name
}
).FirstOrDefault(),
State = d.State.Friends.Select
(
b => new StateModel
{
Id=b.State.Id,
Name = b.State.Name
}
).FirstOrDefault()
}
).SingleOrDefault();
return Json(data);
}
public ActionResult RemoveFriend(int id)
{
Friends friend = db.Friends.Find(id);
db.Friends.Remove(friend);
db.SaveChanges();
return Json(friend);
}
public JsonResult GetCountryState()
{
List<CountryModel> Country = new List<CountryModel>().ToList();
Country.Add(new CountryModel() { Id = 0, Name = "Select Country" });
var Data = db.Country.Select
(
d => new CountryModel
{
Id = d.Id,
Name = d.Name,
State = d.State.Select
(
x => new StateModel
{
Id = x.Id,
Name = x.Name
}
).ToList()
}
).ToList();
Country.AddRange(Data);
return Json(Country, JsonRequestBehavior.AllowGet);
}
public JsonResult GetCountry()
{
var Data = db.Country.Select
(
d => new CountryModel
{
Id = d.Id,
Name = d.Name,
}
).ToList();
return Json(Data, JsonRequestBehavior.AllowGet);
}
public JsonResult GetStateByCountryId(int CountryId)
{
var getStateList = db.State.Where(p => p.CountryId == CountryId).Select(x => new { x.Id, x.Name }).ToList();
return Json(getStateList, JsonRequestBehavior.AllowGet);
}
[HttpPut]
public ActionResult EditFriend(Friends FriendModel)
{
Friends friend = db.Friends.Find(FriendModel.Id);
friend.firstname = FriendModel.firstname;
friend.lastname = FriendModel.lastname;
friend.postalcode = FriendModel.postalcode;
friend.notes = FriendModel.notes;
friend.address = FriendModel.address;
friend.CountryId = FriendModel.Country.Id;
friend.StateId = FriendModel.State.Id;
db.SaveChanges();
var friendModel = new FriendModel();
friendModel.Id = friend.Id;
friendModel.firstname = friend.firstname;
friendModel.lastname = friend.lastname;
friendModel.postalcode = friend.postalcode;
friendModel.notes = friend.notes;
friendModel.address = friend.address;
friendModel.CountryId = friend.CountryId;
friendModel.StateId = friend.StateId;
return Json(friendModel);
}
}
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
"~/Scripts/angular.min.js"));
bundles.Add(new ScriptBundle("~/bundles/appjs").Include(
"~/Scripts/app/customerCtrl.js"));
}
}
Your problem is you are accessing scope inside ng-repeat & Directive like ng-repeat, ng-switch, ng-view, ng-include& ng-if does create a new scope from currently running scope. For referring parent scope method or variable you need use $parent, that provides access to parent
You should first need to read Understanding of Angular Scope Inheritance.
Plunkr for Explanation of the same.
Below is the only change required inside you markup
ng-change="GetStatesList()"
to
ng-change="$parent.GetStatesList()"
Hope this could help you, Thanks.
ng-change event not firing in Angularjs
You have two views .
1. Add record( give info to country ,state)
2. Display stored records (with edit mode to change country,state)
In your add record view ng-change="GetStatesList()" fires and show state list by calling GetStatesList() function friendControllerTest when country selected (model value changed) .
Your **Display records view has its own controller.it doesn't have GetStatesList() function ,so that ng-change not working .
Two solution for this issue is:
1. Make "$scope.GetStatesList()" to "$rootScope.GetStatesList()"- rootscope
2. Write service/factory method then you can use wherever you want.
EDIT:
but using $parent.GetStateList() is good practice as #pankajparkar's soltution

Resources