Im trying to push a data value to an array in AngularJS, with .push();, but I always get this error message:
Error: $scope.test.push is not a function
Here is my HTML:
<div ng-controller="Test">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<div class="page-header"><h1>Testar</h1></div>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
</tr>
</thead>
<tr ng-repeat="info in test"><td>{{info.stracka}}</td><td>{{info.tid}}</td></tr>
</table>
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<div class="form-group" ng-class="{'has-error' : userForm.stracka.$invalid && !userForm.stracka.$pristine, 'has-success' : userForm.stracka.$valid }">
<label>Sträcka(m):</label>
<input type="text" name="stracka" class="form-control" ng-model="form.stracka" required>
<p ng-show="userForm.stracka.$invalid && !userForm.stracka.$pristine" class="help-block">Fel sträcka</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.tid.$invalid && !userForm.tid.$pristine, 'has-success' : userForm.tid.$valid && !userForm.tid.$pristine}">
<label>Tid:</label>
<input type="text" name="tid" class="form-control" ng-model="form.tid" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.tid.$error.minlength" class="help-block">För kort</p>
<p ng-show="userForm.tid.$error.maxlength" class="help-block">För långt</p>
</div>
<button type="submit" class="btn btn-primary">Lägg till</button>
</form>
</div>
</div>
</div>
And here is my controller:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
/*testFactory.testFactoryMethod(function($http) {
$scope.test = data;
});*/
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
$scope.test.push($scope.form);
}).error(function(data, status) {
});
}
};
});
Can anyone help me and explain why I get this message?
Try doing this:
$scope.test = [];
$scope.test.push($scope.form);
Try this:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
/*testFactory.testFactoryMethod(function($http) {
$scope.test = data;
});*/
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
$scope.test = $scope.test || [];
$scope.test.push($scope.form);
}).error(function(data, status) {
});
}
};
});
create an array first -
$scope.usermsg = [];
then push value in it -
$scope.usermsg.push($variable);
Related
I'm creating an app using fake JSONplaceholder API. I'm displaying a list of posts and I want the ng-repeated post titles to link to the post view.
Here's the HTML:
<body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
<h1>{{apptitle}}</h1>
<script type="text/ng-template" id="allposts.htm">
<a href="#addpost">
<button type="button" class="btn btn-primary addbtn" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Add a post
</button>
</a>
View
<select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
<option>9</option>
<option>18</option>
<option>36</option>
<option>100</option>
</select>posts
<div class="row" ng-repeat="collatedPostList in collatedPosts">
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
<div class="inner">
{{post.title}}
<p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
</div>
</div>
</div>
<div class="text-center">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
</div>
</script>
<script type="text/ng-template" id="posts.htm">
</script>
<script type="text/ng-template" id="addpost.htm">
<form ng-submit="addPost()" class="adding">
<input id="titleadd" type="text" name="title" ng-model="newPost.title" placeholder="Add title">
<br>
<input id="textadd" type="text" name="body" ng-model="newPost.body" placeholder="Add some text">
<br>
<button type="submit" ng-click="addAlert(msg,'success')" class="btn btn-primary" id="submit" value="Submit">
Post it
</button>
<a href="#allposts">
<button type="button" class="btn btn-primary" >
Go back to post list
</button></a>
<br>
<uib-alert
ng-repeat="alert in alerts"
type="{{alert.type}}"
dismiss-on-timeout="5000"
close="alerts.splice($index, 1);">{{alert.msg}}
</uib-alert> </form>
</script>
<div ng-view></div>
<script src="app.js"></script>
</body>
and JS:
Array.prototype.collate = function(collateSize) {
var collatedList = [];
if (collateSize <= 0) {
return [];
}
angular.forEach(this, function(item, index) {
if (index % collateSize === 0) {
collatedList[Math.floor(index / collateSize)] = [item];
} else {
collatedList[Math.floor(index / collateSize)].push(item);
}
});
return collatedList;
};
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'allposts.htm',
controller: 'PostsController'
}).when('/posts', {
templateUrl: 'posts.htm',
controller: 'PostController'
}).when('/addpost', {
templateUrl: 'addpost.htm',
controller: 'AddController'
}).otherwise({
redirectTo: '/'
});
});
myApp.controller('PostsController', function($scope) {});
myApp.controller('PostController', function($scope) {});
myApp.controller('AddController', function($scope) {});
myApp.controller('controller', function($scope, $http) {
$scope.apptitle = "My app";
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts"
}).then(function(response) {
$scope.posts = response.data;
$scope.viewby = 9;
$scope.totalItems = $scope.posts.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5;
$scope.collatedPosts = getCollatedPosts($scope.posts);
$scope.newPost = {};
function getCollatedPosts(posts) {
if (!posts) {
return [];
}
var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
return paginatedPosts.collate(3);
}
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.addPost = function(){
$http.post("http://jsonplaceholder.typicode.com/posts",{
title: $scope.newPost.title,
body: $scope.newPost.body,
usrId: 1
})
.success(function(data, status, headers, config){
console.log(data);
$scope.posts.push($scope.newPost);
$scope.newPost = {};
})
.error(function(error, status, headers, config){
console.log(error);
});
};});
$scope.alerts = [];
$scope.msg = "Well done! Your post was added";
$scope.addAlert = function(msg, type) {
$scope.alerts.push({
msg: msg,
type: type
});
};
});
My code is not working. There is 100 ng-repeated posts and I want each post title to link to the post view. Current code links every title to #/posts. I also tried {{post.title}}, but with no success.
What is the correct way to do this?
You can see full code here:
Do following changes::
Codepen :http://codepen.io/ruhul/pen/mAJLEo
1) Remove "/" from your href and use post.id (I believe on a click of link, you will be doing some of the database calls based on postID and will render it to UI ).
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList track by $index"> <div class="inner"> {{post.title}} <p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p> </div>
2) As you are passing parameter add your routing configuration as below::
You can later use this parameter in controller using $routeParams.
.when('/posts/:postId', { templateUrl: 'posts.htm', controller: 'PostController' })
3) Change your controller to this::
myApp.controller('PostController', function($scope,$routeParams,$http) {
console.log($routeParams.postId)
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts/"+$routeParams.postId
}).then(function(response) {$scope.post=response.data});
});
I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.
you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate
I am new to Angular and would like to learn how to accomplish this task below:
I have a dropdown that contains a list of table names from a database. When a table name is selected from the drop down I want to make an HTTP GET call to a web API method which returns the list of column names in the selected table.
HTML:
<div class="row">
<div ng-app="myApp">
<div class="col-lg-12">
<h1>Table Information</h1>
<hr />
<div ng-controller="TableController" class="col-lg-6">
<label>Select a Table:</label>
<select id="tablename" ng-options="table.Name for table in tables track by table.Name" ng-model="data.selectedOption" class="form-control"></select>
</div>
</div>
<div class="col-lg-12">
<h1>{{data.selectedOption}}</h1>
<hr />
<div ng-controller="TableColumnController" class="col-lg-6">
<table class="table">
<thead>
<tr>
<th>Column Name</th>
<th>Type</th>
<th>Max Characters</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tablecolumn in tablecolumns">
<td>
{{tablecolumn.Name}}
</td>
<td>
{{tablecolumn.Type}}
</td>
<td>
{{tablecolumn.MaxCharacters}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Here is my JavaScript:
var app = angular.module('myApp', []);
app.controller('TableColumnController', function ($scope, $http) {
$http.get('http://localhost:61475/api/SxTableInfo/',
{
params: {
tablename: "smsn"
}
}).
success(function (data, status, headers, config) {
$scope.tablecolumns = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});
});
app.controller('TableController', function ($scope, $http) {
$http.get('http://localhost:61475/api/SxTableInfo/').
success(function (data, status, headers, config) {
$scope.tables = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});
});
What is the best way to do this?
Here is just an example of what it looks like:
UPDATED CODE:
<div class="row" ng-app="myApp">
<div ng-controller="ctrl">
<div class="col-lg-12">
<h1>Table Information</h1>
<hr />
<div class="col-lg-6">
<label>Select a Table:</label>
<select id="tablename"
ng-options="table.Name for table in tables track by table.Name"
ng-model="data.selectedOption"
ng-change="getColumns(data.selectedOption)"
class="form-control"></select>
</div>
</div>
<div class="col-lg-12">
<h1>{{data.selectedOption.Name}}</h1>
<hr />
<div class="col-lg-6">
<table class="table table-striped table-hover">
<thead>
<tr>
<th>Column Name</th>
<th>Type</th>
<th>Max Characters</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="tablecolumn in tablecolumns">
<td>
{{tablecolumn.Name}}
</td>
<td>
{{tablecolumn.Type}}
</td>
<td>
{{tablecolumn.MaxCharacters}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
#section Scripts{
<script>
var app = angular.module('myApp', []);
app.factory('tableService', ['$http', function ($http) {
function getColumns(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }).success(function (data) {
return data;
});
}
function getTables() {
$http.get('http://localhost:61475/api/SxTableInfo/').success(function (data) {
return data;
});
}
return { getColumns: getColumns, getTables: getTables }
}]);
app.controller('ctrl', ['$http', '$scope', 'tableService', function ($http, $scope, tableService) {
$scope.tables = tableService.getTables();
$scope.getColumns = function (selection) {
$scope.tablecolumns = tableService.getColumns(selection.Name);
}
}]);
</script>
}
No need for multiple controllers, and you'll need to bind to ngChange. Observe the following example, specifically, the binding to getStuff...
<select
id="tablename"
ng-options="table.Name for table in tables track by table.Name"
ng-model="data.selectedOption"
ng-change="getStuff(data.selectedOption)"
class="form-control">
</select>
app.controller('ctrl', function ($scope, $http) {
$scope.getStuff = function(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', {
params: { tablename: selection }
})
.success(function (data, status, headers, config) {
$scope.tablecolumns = data;
});
}
}
I would recommend moving this logic into an injectable service, most likely your next step. Something like...
app.factory('TableService', ['$http', function($http) {
function getMetaData(selection) {
$http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }
}
return { getMetaData: getMetaData }
}]);
app.controller('ctrl', ['$scope', 'TableService', function ($scope, TableService) {
$scope.getStuff = function(selection) {
TableService.getMetaData(selection).then(function(response) {
$scope.tablecolumns = response.data;
});
}
}]);
Plunker Link - simplified demo
Edit per your example and updated code, give this a shot...
app.controller('ctrl',...
tableService.getTables().then(function(response) {
$scope.tables = response.data;
});
$scope.getColumns = function (selection) {
tableService.getColumns(selection.Name).then(function(response) {
$scope.tablecolumns = response.data
});
}
You should not use two controllers for this purpose, instead you can use a service or factory for $https request to get you data from the server.
You should also use ng-change to invoke table column name info call
Try this
in app.js
var app = angular.module('plunker', []);
app.factory('userFactory', ['$http', function($http) {
var dataFactory = {};
dataFactory.getTableNames = function() {
/*$http.get('http://localhost:61475/api/SxTableInfo/').
success(function (data, status, headers, config) {
$scope.tables = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});*/
data = [{
id: 1,
tableName: 'table1'
}, {
id: 2,
tableName: 'table2'
}, {
id: 3,
tableName: 'table3'
}];
return data;
}
dataFactory.getColumnNames = function() {
alert('implement your logic here . ');
/* $http.get('http://localhost:61475/api/SxTableInfo/',
{
params: {
tablename: "smsn"
}
}).
success(function (data, status, headers, config) {
$scope.tablecolumns = data;
}).
error(function (data, status, headers, config) {
alert("error!");
});*/
}
return dataFactory;
}]);
app.controller('MainCtrl', ['$scope', 'userFactory', function($scope, userFactory) {
$scope.name = 'World';
$scope.items = userFactory.getTableNames();
$scope.getColumnNames= function(){
userFactory.getColumnNames();
}
}]);
in HTML,
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<select ng-change="getColumnNames()" ng-model="selectedItem" ng-options="item.tableName as item.tableName for item in items"></select>
</body>
</html>
Plunker link for the same.
Search form xmlhttprequest works fine.
is there any option to use this function while typing instead of submit form ?
function customersController($scope, $http) {
$scope.search = function() {
$scope.url = 'http://www.vanmaram.com/json_result.php?en=' + $scope.keywords;
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in <li> element
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords">
<input type="submit" value="Search">
</form>
<ul>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
</div>
Hi Please check this example in plunkr [link:http://plnkr.co/edit/6kuVR4?p=preview]
Hope it helps.
Js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected = "";
$scope.countries = ["India", "Australia", "Japan"];
});
app.directive('autoComplete', function($timeout) {
return function(scope, iElement, iAttrs) {
iElement.autocomplete({
source: scope[iAttrs.uiItems],
select: function() {
$timeout(function() {
iElement.trigger('input');
}, 0);
}
});
};
});
In HTML
<body ng-controller="MainCtrl">
<p>Countries {{countries|json}}!</p>
<div ng-app="MyModule">
<div>
<input auto-complete="" ui-items="countries" ng-model="selected" />selected = {{selected}}
</div>
</div>
</body>
used library jqueryui/1.8.16/jquery-ui.js
The solution found with ng-change which call the same function of form submit
function customersController($scope, $http) {
$scope.suggestword = function(argument) {
$scope.url = 'http://www.vanmaram.com/ajax_json_suggestion.php?en=' + $scope.keywords; // The url of our search
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.suggetionresult = data; // Show result from server in <li> element
$scope.result = null;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords" ng-change="suggestword()">
<input type="submit" value="Search">
</form>
<ul ng-if='result.length'>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
<div id="suggestion" ng-if='suggetionresult.length > 1'>
Suggestions: <a ng-repeat="word in suggetionresult | limitTo:9">{{ word }}</a>
</div>
</div>
I'm trying to write a simple angularapp to allow the teachers to edit their class information. I'm using angular-ui dialog directive to get the lightbox. On userclick I've written a function to pass the data to the modal and open the dialog. But for some reason the data is not properly binded.
This is my controller.js
'use strict';
define(['app' ], function(app) {
app.controller('TeacherClasses',
[ '$scope', '$http', '$dialog','$location', 'teacherClassService',
function($scope, $http, $dialog, $location, teacherClassService) {
$scope.newClass={};
$scope.show = {"createClassModal": false};
$http.get('/grades').success(function(data) {
$scope.grades = data;
});
$scope.newClass.grade = "Grade";
$scope.setGrade = function(grade){
$scope.newClass.grade = grade;
};
$scope.fetchStudentGroups = function(){
$http.get('/teacher/studentGroups').success(function(data) {
$scope.studentGroups = data;
});
};
$scope.fetchStudentGroups();
$scope.createClass = function(){
$http.post('/studentGroup', $scope.newClass).
success(function(data, status, headers, config) {
$scope.show.createClassModal = false;
//Clearing it out for next time
$scope.newClass = {};
$scope.fetchStudentGroups();
}).
error(function(data, status, headers, config) {
});
console.log($scope.newClass);
};
$scope.openDialog = function(studentGroup, dialog){
$scope.newClass = angular.copy(studentGroup);
$scope.opts = {
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '/assets/partials/teacher/manage/editClassInfo.html',
resolve: {
data: function(){
return $scope.newClass;
}
}
};
var modal = $dialog.dialog($scope.opts);
modal.open();
}
}]);
return app;
});
And this is my partial
<div class="modal-header">
Edit Class
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<input type="text" ng-model="newClass.name" class="span4">
</div>
<div class="control-group">
<select ui-select2 data-placeholder="Choose a grade" id="grades" class="span4">
<option></option>
<option ng-repeat="grade in grades" ng-model="grades" >{{grade}}</option>
</select>
</div>
<label>Students {{newClass.noOfStudents}}</label>
<label>{{newClass.name}}</label>
</form>
</div>
<div class="modal-footer"></div>
My module definitions are in app.js
'use strict';
define([ 'angular' ], function(angular) {
var myModule = angular.module('myApp',
[ 'ngResource', 'ui', 'infinite-scroll', 'ngDragDrop', 'blueimp.fileupload','ui.bootstrap.dialog', 'ui.bootstrap.modal',
'ui.bootstrap.dropdownToggle', 'LoadingIndicator', 'http-auth-interceptor']);
myModule.value('ui.config', {
select2 : {
allowClear : true
},
redactor: {
plugins: ['fullscreen']
}
});
return myModule;
});
But none of these values are tied back to the view. What am I doing wrong here?