I mixed EJS and AngularJS in a webapp, but now I'm having problems to load a default value for a dropdown (select element).
I use the same HTML file to add and update users.
I have a URL that return all values loaded in the dropdown, accessed in the Angular controller when the page loads.
This is the controller:
angular.module('app').controller('userCtrl', function($scope, $http) {
...
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
});
}
The EJS sends the default value via response (as in this example):
router.get('/user', function(req, res) {
res.render('pages/user', { defatultCity: 10 });
}
The HTML builds the dropdown with this code:
<select id="city" name="city" class="form-control input-sm" required>
<option></option>
<option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>
</select>
What I have 'unsuccessfully' tried so far (in the HTML):
To validate value from Angular with value from EJS
<option ng-repeat="x in cities" value="{{x.idCity}}" <%if (defaultCity == %> {{x.idCity}} <%) {%> selected <%}%> > {{ x.Nome }} </option>
To insert a hidden input to hold the value in the HTML and inside the controller I added a JQuery
<input type="hidden" id="defaultCity" value"<%=defaultCity%>" />
// In the controller (it return an error - this.each is not a function)
$('city').val($('#defaultCity'))
I know these attempts are ugly, but I could not find a way to make it work yet. I'll be happy if someone knows how to do it.
PS: I would like to avoid passing all the city list of values from NodeJS to use EJS forEach command inside the HTML.
Thank you!
Add this piece of code at the end of your .ejs template
<script type="text/javascript">
angular.module('app')
.value('myCity', <%- JSON.stringify(defaultCity) %>);
</script>
then inject the component in your controller:
app.controller('myCtrl', function ($scope, myCity) {
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities = response.data.records;
// myCity must be an object - same as vm.cities[0], for example
$scope.defaultCity = myCity;
});
});
and change your HTML file to have the default value
<select ng-model="defaultCity"
ng-options="city as city.name for city in cities track by city.id"
id="city" name="city" class="form-control input-sm" required >
<option></option>
</select>
Related
I'm currently working on an AngularJS project and I would like to print option selected on a drop down list together with input data that has been entered by the user without using the backend. How can this be done using AngularJS? Any help?
I believe you wanted something like Prefix + Name, her https://jsfiddle.net/datachand/szc550yb/3/
<div ng-controller="UserCtrl as vm">
<select ng-model="vm.prefix">
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
<input type="text" ng-model="vm.name" placeholder="Enter your Name">
<button ng-click="vm.submit()">
Send
</button>
</div>
A controller is needed at any case, even if it's empty:
angular.module('app', []);
function UserCtrl ($log) {
$log.log('UserCtrl');
var vm = this;
vm.submit = function () {
$log.log(vm.prefix, vm.name);
$window.location.href = "https://towhateverurl" + "?prefix=" + vm.prefix +"&name=" + vm.name;
}
UserCtrl.$inject = ['$log'];
angular.module('app').controller('UserCtrl', UserCtrl);
I hope this is what, is required.
Can you help me please? I have no idea of what this can be.
I'm using a template on my pages and each page has yours file js with angularJS code:
~/Content/Scripts/layout/index.js
~/Content/Scripts/home/home.js
~/Content/Scripts/projetos/projetos.js
I'm trying to call a function when the dropdown value changes, so i using ng-change in a partial-view.
My page _Layout:
<html lang="en" class="no-js" ng-app="App">
...
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</div>
</div>
<!-- END CONTENT -->
My partial-view is loaded when event click on menu occurrs
<div ng-cloak ng-controller="ProjetosController" ng-init="init()">
...
<div class="col-md-3">
<label>Projetos</label>
<div class="input-icon input-icon-lg">
<select ng-change="changed()" data-placeholder="selecione..." class="form-control input-lg select2me" ng-model="Projetos"
ng-options="proj.Nome for proj in Projetos">
<option value=""></option>
</select>
</div>
But nothing happens and any error occurred when I look in Chrome's developer tools.
My controller c#
public JsonResult LoadProjetos()
{
var results = rep.LoadProjetos();//List<Projetos>();
return Json(new
{
projetos = results
}, JsonRequestBehavior.AllowGet);
}
My controller js
var app = angular.module('App');
app.controller('ProjetosController', function ($scope, $http) {
$scope.init = function () {
$("#menu").find('li#projetos').addClass("start active");
$http({
method: 'GET',
url: 'Projetos/LoadProjetos'
}).then(function successCallback(response) {
var projetos = response.data.projetos;
$scope.Projetos = projetos;
}, function errorCallback(response) {
alert(response);
});
}
$scope.changed = function () {
alert('text');
}
});
Any ideas? Thanks all
Try these changes so that your select uses a $scope variable:
<select ng-change="changed()" data-placeholder="selecione..." class="form-control input-lg select2me" ng-model="selectedItem"
ng-options="proj.Nome for proj in Projetos">
<option value=""></option>
</select>
$scope.changed = function () {
alert($scope.selectedItem);
}
http://plnkr.co/edit/uUf9ehxQpBSzVgQasTtN?p=info
If you use AngularJS version 1.2.x and the newest Chrome see this:
https://code.google.com/p/chromium/issues/detail?id=565132
updated to 1.4.5 This should work.
After a long time, i found a solution. The problem is because my ng-model has the same name of the ng-option. I changed it and works fine!
Thx all.
I am creating a custom filter in angular js this is my html,
<div class="box-body">
<div class="form-group">
<label>Page-Title:</label>
<input type="text" required value="" data-ng-model="title" name="page_title" class="form-control" id="" placeholder="Enter Page Title">
</div>
<div class="form-group">
<label>Page-Alias:</label>
<input type="text" value="#{{ title | replaceSpace}}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
</div>
This is my angular js code
var app = angular.module('CustomAngular', []);
app.controller('CustomCtrl', function ($scope) {
app.filter('replaceSpace', function () {
return function (input) {
return input.replace(/ /g, '-').toLowerCase();
};
});
});
The filter is not working and also I get error in the console.
Error: [$injector:unpr] http://errors.angularjs.org/1.3.15/$injector/unpr?p0=slugifyFilterProvider%20%3C-%20slugifyFilter
at Error (<anonymous>)
If I use filter: infront of the filter name I donot get any errors in console but it's still not working.
<input type="text" value="#{{ title | filter:replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
You don't put filters inside of a controller, put it after your var app line. It's a separate thing just like controllers / directives / etc.
var app = angular.module('CustomAngular', []);
// Here's where it goes
// Also now any/all controllers can use it!
app.filter('replaceSpace', function () {
return function (input) {
return input.replace(/ /g, '-').toLowerCase();
};
});
app.controller('CustomCtrl', function ($scope) {
});
You should define filter outside of controller and not use filter: as it has different meaning, that's the correct way to use your filter
<input type="text" value="#{{ title | replaceSpace }}" name="page_alias" class="form-control" id="" placeholder="Auto-Generated If Left Blank">
although you should either initialize model by $scope.title = '' or place a check in your filter to run replace only when input is defined, otherwise you will get JS errors
filter: is used to filter the array from model, and when you pass another filter to it it does nothing
Was trying my hands at angularjs with ejs to run a for loop on an integer array received on the ejs template from an angularjs controller.
Following is the code for that:
<div class="form-group" ng-controller="MyController as myCtrl">
<div><label>Trying to run the for loop on {{myCtrl.getMyIntegerArray()}} array</label></div>
<select class="form-control input-xsmall inline">
<option>Year</option>
<% for(var i=0; i <= {{myCtrl.getMyIntegerArray().length}}; i++) { %>
<option>{{myCtrl.getMyIntegerArray()[i]}}</option>
<% } %>
</select>
</div>
Could somebody help me with it?
There is no need to use ejs here, angularjs has its own template engine.
You can achieve what you want by using ng-repeat like this:
<select class="form-control input-xsmall inline">
<option>Year</option>
<option ng-repeat="value in myCtrl.getMyIntegerArray()">{{value}}</option>
</select>
But it's better to store the result in a $scope like this in the controller:
app.controller('MainCtrl', function($scope) {
this.getMyIntegerArray = function () {
return [1234, 5678, 9012, 3456];
};
$scope.myIntegerArray = this.getMyIntegerArray();
});
and in html:
<select class="form-control input-xsmall inline">
<option>Year</option>
<option ng-repeat="value in myIntegerArray">{{value}}</option>
</select>
Example plunker: http://plnkr.co/edit/IttzGJfOzYdP9Du0uAPh?p=preview
Hope this helps.
I have problem with angular modal value.
I have $rootScope and on button im opening modal which contains , and I can't set default / selected value to that
<form>
<input type="button" class="mobileUpdate" ng-click="openMobileUpdateModal()" />
<script type="text/ng-template" id="mobileModal.html">
<form name="modalForm">
<div class="modal-body">
<p>Country</p>
<select id="countryMobile" ng-model="countryMobile" class="select-styled" name="countryMobile" required>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<input type="button" ng-click='confirm()' value="OK"/>
<input type="button" ng-click='cancel()' value="Cancel"/>
</div>
</form>
</script>
</form>
$rootScope.openMobileUpdateModal = function () {
$rootScope.countryMobile = $rootScope.country;
var modalInstance = $modal.open({
templateUrl: 'mobileModal.html',
controller: ModalInstanceCtrl
});
};
var ModalInstanceCtrl = function ($rootScope, $modalInstance) {
$rootScope.confirm = function () {
//do something
$modalInstance.close();
};
$rootScope.cancel = function () {
$modalInstance.dismiss();
};
};
Anyone know how to send value from $rootScope to modal, and set that value as default?
Thanks
First of all there is syntax error you have double quote twise in you select tag code. Update it as below then try. And use $root in your ng-model.
<select id="countryMobile" ng-model="$root.countryMobile" class="select-styled" name="countryMobile" required>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
I'm not sure that I understand your problem correct but try do not use rootScope or modify and avoid rootScope modification.
If you need use some value from rootScope:
extract this value to local scope of particular controller and
after that use it
Use WATCH operator to avoid situations when you
render some value before it initialised.
<option ng-repeat> does not work in angularjs.
you should use
<select id="countryMobile" ng-model="countryMobile" class="select-styled" name="countryMobile" required ng-options="country.id as country.name for country in contries"></select>
http://docs.angularjs.org/api/ng/directive/select