Failed to append after $http .then() - javascript

Hello I'm using angular js $http to get json data
json Data
{"Data":["index":[{"Name":"append_here_1"},{"Name":"append_here_2"}]]}
App.js
var app=Angular.module('app',[]);
Request.js
app.service('Request_service', function() {
this.get_json=function(){
return $http.post('http://...', {
params_1: "123",
params_2: "abc"
}).then(function success(e) {
return e.data;
},function fail(e){
return false;
});
}
});
Controller.js
$scope.index_data=[];
app.controller('myCtrl', function($scope, Request_service) {
Request_service.get_json().then(function(data)
$scope.index_data=data.Data[0].index;
for(var i=1;i<3;i++){
var id_data="#append_here_"+i;
$(id_data).append('<input value="'+i+'">');
}
);
});
template.html
<body ng-app="app">
<div ng-controller="myCtrl">
<div ng-repeat="obj in index_data ">
// {{index_data.Name}} = append_here_1
<div id="{{index_data.Name}}">
</div>
<div>
the problem is when the controller load the data it does not append
<div id="append_data_1">
</div>
<div id="append_data_2">
</div>
what it should look like
<div id="append_data_1">
<input value="1">
<input value="2">
</div>
<div id="append_data_2">
<input value="1">
<input value="2">
</div>
It will be appreciate if anyone could improve this code
thank you in advance

Modify this function declaration
function get_json () {
var deferred = $q.defer();
$http.post('http://...', {
params_1: "123",
params_2: "abc"
})
.success(function (result) {
deferred.resolve(result.data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
And modify your html code
<div ng-repeat="obj in index_data ">
// {{obj.Name}} = append_here_1
<div id="{{obj.Name}}">
{{obj.Name}}
</div>
<div>

Related

ng-repeat values in single input with comma separated

I have list array.Inside that I have one nested array called types.I am trying to show types.work inside an input field with comma separated.
This is what I have tried:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="list.name">
<label ng-repeat="data in list.types">{{data.work}}{{$last ? '' : ', '}}</label>
</div>
</div>
Can anyone tell me that how to use ng-repeat values in single input?.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.input_model_value = ''
var temp = []
$scope.list.forEach(function(t1){
t1.types.forEach(function(val){
temp.push(val.work)
})
})
$scope.input_model_value = temp.join(',')
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="input_model_value">
<label ng-repeat="data in list.types">{{data.work}}</label>
</div>
</div>
use multiple ng-repeat to access the nested array.
<label ng-repeat="data in list">
<label ng-repeat="d in data.types">
{{d.work}}
</label>
</label>
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.name = $scope.list[0].types.map((o) => o.work)
$scope.name = $scope.name.join(",")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="name">
<label ng-repeat="data in list">
<label ng-repeat="d in data.types">
{{d.work}}
</label>
</label>
</div>
</div>
In case You want some other solution. You can iterate over your array in JS file and assign the value to your input model.
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script>
<body>
<div ng-app="app">
<div ng-controller="MainCtrl" ng-init="init()">
<input type="text" ng-model="listData">
</div>
</div>
</body>
<script>var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.init = function(){
$scope.list=[
{
"name":"john",
"types":[
{"work":"aa"},
{"work":"bb"}
]
}
];
$scope.listData = "";
for(var i=0;i<$scope.list[0].types.length;i++){
if($scope.listData!= undefined){
$scope.listData = $scope.listData+","+$scope.list[0].types[i].work;
}
}
}
});
</script>
</html>
You added the list an array so you can use ng-repeat in ng-repeat or you can directly use array first object like this
<input type="text" ng-model="list[0].name">
<label ng-repeat="data in list[0].types">{{data.work}}{{$last ? '' : ', '}}</label>

User input not binding from $scope.$watch

Just getting started with Angular and I've spent the last 2 days trying to figure out how to bind data from a new search through a service. I had the search working before with the following code before using a service:
SearchController.js
function SearchController($scope, $http){
$scope.search = ""
$scope.getGames = function (){
return $http.get("https://igdbcom-internet-game-database-v1.p.mashape.com/games/?fields=name%2Crating%2Ccover%2Curl%2Csummary%2Cfirst_release_date&limit=50&offset=0&order=release_dates.date%3Aasc&search=" + $scope.search, {"headers": {
"x-mashape-key": "KEY",
"accept": "application/json",
}
})
.success(function(resp){
$scope.games = resp
})
.error(function(data){
console.log(data)
})
}
$scope.getGames()
};
SearchController.$inject = ['$scope', '$http']
angular
.module('app')
.controller('SearchController',SearchController)
search.html
<div class="container">
<div ng-controller="SearchController">
<div class="col-md-6 col-md-offset-4">
<h1>Search for Game</h1>
<form name="form">
<input name="search" ng-model="search" ng-change="getGames()"
ng-model-options="{debounce: 1000}" placeholder="Type Game"
minlength="3"
required="required" />
<div ng-messages="form.search.$error" ng-if="form.search.$touched">
<div ng-message="required">Please type a game to search.</div>
<div ng-message="minlength">3 characters required</div>
</div>
</form>
</div>
<div class="row fix-heights">
<div class="col-md-6" ng-repeat="game in games | filter: search" class="row-eq-height">
<br>
<div class="media">
<div class="media-left">
<img class="pull-left" src="https://res.cloudinary.com/igdb/image/upload/t_thumb/{{ game.cover.cloudinary_id }}.jpg">
</div>
<div class="media-body">
<p>Title: {{ game.name }}</p>
<p>Release Date: {{ game.first_release_date | date:'mediumDate'}}
<p>Short Description: {{ game.summary }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
So my first attempt was successful but when I tried to move the code to a service I am unable to automatically update and bind the data from the new search. I've tried to use $scope.$watch and I can see the url change in the console but the results do not populate in my search.html. Below are the new changes.
function SearchController($scope, $http, GetGameService){
$scope.search = ""
search = $scope.search
GetGameService.getGames(search)
.success(function(resp){
$scope.games = resp
console.log(resp)
})
.error(function(data){
console.log(data)
})
$scope.$watch('search', function(){
search = $scope.search
GetGameService.getGames(search)
})
};
SearchController.$inject = ['$scope', '$http', 'GetGameService']
angular
.module('app')
.controller('SearchController',SearchController)
/////////GetGameService.js
function GetGameService($http){
this.getGames = function(search) {
return $http.get("https://igdbcom-internet-game-database-v1.p.mashape.com/games/?fields=name%2Crating%2Ccover%2Curl%2Csummary%2Cfirst_release_date&limit=50&offset=0&order=release_dates.date%3Aasc&search=" + search, {"headers": {
"x-mashape-key": "KEY",
"accept": "application/json",
}
})
}
}
GetGameService.$inject = ["$http"]
angular
.module('app')
.service("GetGameService", GetGameService);
<div class="container">
<div ng-controller="SearchController">
<div class="col-md-6 col-md-offset-4">
<h1>Search for Game</h1>
<form name="form">
<input name="search" ng-model="search"
ng-model-options="{debounce: 1000}" placeholder="Type Game"
minlength="3"
required="required" />
<div ng-messages="form.search.$error" ng-if="form.search.$touched">
<div ng-message="required">Please type a game to search.</div>
<div ng-message="minlength">3 characters required</div>
</div>
</form>
</div>
<div class="row fix-heights">
<div class="col-md-6" ng-repeat="game in games | filter: search" class="row-eq-height">
<br>
<div class="media">
<div class="media-left">
<img class="pull-left" src="https://res.cloudinary.com/igdb/image/upload/t_thumb/{{ game.cover.cloudinary_id }}.jpg">
</div>
<div class="media-body">
<p>Title: {{ game.name }}</p>
<p>Release Date: {{ game.first_release_date | date:'mediumDate'}}
<p>Short Description: {{ game.summary }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
Apologies for any wrong format and many thanks for any help!
The primary error is you are missing the $scope.games assign inside your $watch
I'm not sure whether you really want to call getGames on init, or intend to use it as a function.
The controller can be reorganized to reduce code replication
function SearchController($scope, $http, GetGameService){
$scope.search = ""
// getGames(); // if you need to call on init, call here
$scope.$watch('search', function(){
getGames();
})
function getGames() {
return GetGameService.getGames($scope.search)
.then(function(resp){ // it's better to use .then than .success
$scope.games = resp
console.log(resp)
}, function(data){
console.log(data)
})
}
};

Angularjs - Displaying data using $http get from remote server

i want to send a http get request which is not a problem.
But the problem is i want to disply the data from the server page. Does it has to be a JSON page to display the data from remote server ? or any sort of data can be displayed ? if yes , then how
Thank you
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p> <!-- 1 -->
<p>
<ul ng-repeat="post in posts">
<li>{{post}}</li>
</ul>
</p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.callAPI = function() { // 2
//console.log($scope.url); //3
$http.get($scope.url)
.success(function(response) {
$scope.posts = response.data; //4
});
};
});
</script>
</body>
</html>
another version of code
<div class="form" ng-app="myApp" ng-controller="myCtrl">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="callAPI()" /> </p>
<div ng-bind="result"></div> <!-- 5 -->
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.$watch('url', function() {
fetch();
});
function fetch() {
console.log($scope.url);
$http.get($scope.url)
.success(function(response) {
$scope.result = response.data;
});
}
$scope.callAPI= function() {
this.setSelectionRange(0, this.value.length);
}
});
</script>
</body>
</html>
Like the comments says, I believe that angular look at the content Type of the response to parse the data. Have you try added the accept header type?
What is the content type of the response?
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Accept': change this to whatever content you want to accept
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
hey i have found my answer of my question ...
there was a mistake in the source code
here is the right one
<div class="form" ng-app="myApp" ng-controller="myCtrl as controller">
<p>Enter URL : <input type="text" ng-model="url" /></p>
<p><input type="submit" value="CHECK" ng-click="clickButton()" /> </p>
<p>
<ul>
<li ng-repeat="data in result">
{{data}}
</li>
</ul>
</p>
</div>
and
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.clickButton = function() {
console.log($scope.url);
$http.get($scope.url)
.then(function(response) {
$scope.result = response.data;
});
};
});
</script>
:)
if anyone has a similer problem , i hope this answer will help ..
cheers
function functionName(){
$http.get(URL).success(function(response){
$scope.variable = response;
})
}
inside get() put your url, if your url returning any data then it will go to success() function.

AngularJS move part of Controller to Service

Consider the following code.
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link href="/css/overlay-control.css" rel="stylesheet">
<link href="/css/list-control.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--<script src="/js/Services/UserService.js"></script>-->
<script src="/js/Controllers/MainController.js"></script>
<!--<script src="/js/Controllers/UserController.js"></script>-->
<script src="/js/bootstrap.min.js"></script>
</head>
<body ng-controller="MainController as myControl">
<div id="overlaycover" ng-click="myControl.showUpd(0)"></div>
<div id="overlaybox">
<div class="col-md-12">
<h4>Update:</h4>
<form ng-submit="myControl.updTodo()">
<div class="form-group">
<label for="updContent">Note:</label>
<textarea rows="5" cols="30" class="form-control" id="updContent" name="updContent" ng-model="noteupd.content"></textarea>
</div>
<div class="form-group">
<label for="updDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" class="form-control" id="updDeadline" name="updDeadline" ng-model="noteupd.deadline" />
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="updCompleted" name="updCompleted" ng-model="noteupd.completed" /> - Completed
</label>
</div>
<div class="form-group">
<input type="hidden" id="updID" ng-model="noteupd.id" /><br/>
<button type="submit" class="btn btn-info">Update</button>
</div>
</form>
Click utside the square to close.
</div>
</div>
<div class="container">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="listDiv">
<h1>Todo-list:</h1>
<p>
<img src="/images/legend-normal.png"> - Unfinished 
<img src="/images/legend-completed.png"> - Finished 
<img src="/images/legend-late.png"> - Late
</p>
<table class="table" id="list-table">
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
<th colspan="2">Modify:</th>
</tr>
<tr ng-repeat="todo in myControl.todos" ng-class="rowClass(todo.completed, todo.deadline)">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button type="button" class="btn btn-info" ng-click="myControl.showUpd(todo.id)">Update</button></td>
<td><button type="button" class="btn btn-danger" ng-click="myControl.delTodo(todo.id)">Delete</button></td>
</tr>
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12" id="formDiv">
<h3>Add new note:</h3>
<form ng-submit="myControl.addTodo()">
<div class="form-group">
<label for="newUser">User:</label>
<select ng-model="noteadd.user" class="form-control" id="newUser" name="newUser">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newProject">Project:</label>
<select ng-model="noteadd.project" class="form-control" id="newProject" name="newProject">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
</div>
<div class="form-group">
<label for="newContent">Note:</label>
<textarea rows="5" cols="30" ng-model="noteadd.content" class="form-control" id="newContent" name="newContent"></textarea><br/>
</div>
<div class="form-group">
<label for="newDeadline">Deadline (format YYYY-MM-DD HH:MM:SS):</label>
<input type="text" ng-model="noteadd.deadline" class="form-control" id="newDeadline" name="newDeadline" /><br/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Add</button>
</div>
</form>
</div>
</div>
</body>
</html>
AngularJS Controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$scope.noteadd = {};
var noteadd = $scope.noteadd;
$scope.noteupd = {};
var noteupd = $scope.noteupd;
// Get all notes:
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
// Get all users:
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
// Get all projects
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
// Add note to database
thisApp.addTodo = function(noteadd)
{
$http({
method : 'PUT',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteadd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
};
// Hide note by setting removed to 1
thisApp.delTodo = function(noteID)
{
var r = confirm("Are you sure?");
if (r == true) {
var noteObj = JSON.parse('{"id":' + noteID + '}'); // JSON for req
$http({
method : 'DELETE',
url : 'http://localhost:8000/notes',
data : $.param(noteObj),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't delete note. Please try again!");
});
}
};
// Show overlay with form for updating a note
thisApp.showUpd = function(noteID)
{
var overlaycover = document.getElementById("overlaycover");
var overlaybox = document.getElementById("overlaybox");
overlaycover.style.opacity = .65;
if(overlaycover.style.display == "block" || noteID == 0){ // For toggling overlay
overlaycover.style.display = "none"; // Hide div overlaycover
overlaybox.style.display = "none"; // Hide div overlaybox
} else {
$http({method : 'GET', url : 'http://localhost:8000/notes/' + noteID})
.then (function(response) {
noteupd.content = response.data.content; // Update fields in form
noteupd.deadline = response.data.deadline;
noteupd.id = response.data.id;
if (response.data.completed == 1) {
noteupd.completed = true;
} else {
noteupd.completed = false;
}
overlaycover.style.display = "block"; // Show div overlaycover
overlaybox.style.display = "block"; // Show div overlaybox
}, function() {
alert("Error getting todo note");
});
}
}
// Update a note
thisApp.updTodo = function(noteupd)
{
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.noteupd),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function(response) {
location.reload();
}, function() {
alert("Couldn't add note. Please try again!");
});
}
// Check if deadline passed for each note in list
$scope.rowClass = function(completed, deadline)
{
var nowTime = Math.floor(Date.now()/1000);
var deadTime = new Date(deadline);
var deadUTC = Math.floor(deadTime/1000);
if (completed == 1) {
return "success"; // Note is completed
} else if (deadUTC < nowTime) {
return "danger"; // Note is not completed, deadline passed
} else {
return "active"; // Note is not completed, still time left
}
}
});
What I would like to do is to move all $http-calls to a service instead of having them in the controller like I have it now. I have searched the internet but I don't really understand the solutions i've found there.
Second, in several functions, as you can see, I use location.reload();. I would like to use ng-bind instead, but as the sam, I don't understand how this works.
Can someone please explain how I should do these two things?
Ok , let's for example create a Users factory and put all Users api related stuff inside:
'use strict';
angular
.module('todoApp')
.factory('Users', factory);
function factory($http) {
var service = {
get: get,
//edit: edit ...
};
return service;
function get() {
return $http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
return response.data;
});
}
//function edit(user) {
// return $http({method : 'PUT...
//}
}
What you have to do next is inject that factory wherever you want to call it.
So in your controller you essentially have to do this:
angular.module('todoApp', [])
.controller('MainController', function($scope, Users) {
//.....
function getUsers() {
Users.get().then(function(data){
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
}
getUsers();
//...
Repeat the same by creating the appropriate services for notes and projects.
To not bloat the main app.js move this services to seperate files, users.service.js etc..
I would also advise you to move the controllers to seperate files too.
Just be careful:
this is a module creation
angular.module('todoApp', [])
You create a module once.
to attach a service/factory/controller/anything, when you are in that separate file, to that module you use this:
angular.module('todoApp').anything
Second, I assume you use location.reload to update the view with the new data.
Let's say you edit/delete a User. Instead of reloading the page, call getUsers() in the then() of put/delete/create User.
Hope it makes sense to you!
PS: This styleguide by John Papas have been very helpful to me, I suggest you give it a read !
I've already used service factory solution for such kind of problem.
angular.module('data-service').factory('dataService', ['$http',function ($http) {
var url = 'http://localhost:8000/';
return {
getData: function(type) {
return $http({method : 'GET', url : url + type});
},
allData: function() {
return $q.all({
notes: this.getData('notes'),
users: this.getData('users'),
projects: this.getData('projects')
});
}
}
}]);
usage:
dataService.getData('notes').then(function (data) { ... });
also you can use angular promise $q.
dataService.allData().then(function(data) { /* data.notes, data.users, data.projects */ }

Update textfield value with ajax data using angular js

I am using angular js directives for bootstrap. What i am trying for is to create an edit form on bootstrap modal when user clicks on edit button from list of items. Here is my code:
HTML:
<div class="modal-header">
<h3>Edit Template</h3>
</div>
<div class="modal-body">
<form name="form" class="form-horizontal" novalidate>
<fieldset>
<div class="span4" ng-class="smClass" ng-show="etemplate.status">{{etemplate.status}}</div>
<div class="control-group">
<label class="control-label" for="etemplateName">Name</label>
<div class="controls">
<input class="input-xlarge" id="etemplateName" ng-model="eTemplate.name" maxlength="150" type="text" required />
</div>
</div>
<div class="control-group">
<label class="control-label" for="etemplateDesc">Description</label>
<div class="controls">
<textarea id="templateDesc" id="etemplateDesc" ng-model="eTemplate.desc"></textarea>
</div>
</div>
<div class="center">
<input type="text" style="display:none;" ng-model="eTemplate.id" value="{{eTemplate.id}}" required />
<button type="button" ng-click="update(eTemplate)" class="btn btn-primary" ng-disabled="form.$invalid || isUnchanged(eTemplate)">Submit</button>
<button class="btn" ng-click="cancel()">Cancel</button>
</div>
</fieldset>
</form>
</div>
Controller:
controller('TemplateController', ['$scope', '$http', '$modal', function($scope, $http, $modal) {
var tmpId = '';
$scope.openEdit = function(id) {
tmpId = id;
var editTmpModalInstance = $modal.open({
templateUrl: 'editTemplateContent.html',
controller: 'ETModalInstance'
});
$http({
method: 'GET',
url: adminBaseUrl+'/get_template/',
params: {'id': tmpId}
}).
success(function(data, status, headers, config) {
$scope.$broadcast('EditTemplateDataReached', data);
}).
error(function(data, status, headers, config) {
});
}
}]).
controller('ETModalInstance', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance) {
$scope.emaster = {};
$scope.smClass = '';
$scope.eTemplate = {};
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
$scope.isUnchanged = function(eTemplate) {
return angular.equals(eTemplate, $scope.master);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.update = function(eTemplate) {
var strng = $.param(eTemplate);
};
}]).
My work around for achieving this is when user clicks on edit button id of selected item is passed in my controller which sends an ajax request to server and then fill the fields with respective values. However my fields are not populated when ajax data is returned.
Found the problem in my code i was using $scope for broadcasting and catching the data whereas i have to use $rootScope.
Wrong:
$scope.$broadcast('EditTemplateDataReached', data);
$scope.$on('EditTemplateDataReached', function(data) {
$scope.eTemplate = data;
$scope.$apply();
});
Correct:
$rootScope.$broadcast('EditTemplateDataReached', data);
$rootScope.$on('EditTemplateDataReached', function(e, data) {
$scope.eTemplate = data;
$scope.$apply();
});

Categories

Resources