Clear Child Scope in ng-include on Template Change - javascript

I have HTML Code like:
<select ng-model="category" ng-change="categoryChanged(category)" class="form-control"
data-ng-options="category as category.name for category in categories">
<option value="">All Categories</option>
</select>
<div ng-include="subCategoryTemplate"></div>
My Controller Code is:
$scope.categoryChanged= function (category) {
if (category) {
templateService.getSubCategoryTemplate({ categoryId: category.id }).$promise.then(
function (model) {
if (model) {
$scope.subCategoryTemplate = model.subCategoryTemplate;//Here I am getting on Template Path from the server
$scope.carCompanies = model.carCompanies;
}
},
function (error) {
});
}
$scope.filer = function () {
alert($scope.selectedCarCompany.id);
}
};
Template HTML is:
<select ng-model="$parent.selectedCarCompany" class="form-control"
data-ng-options="carCompany as carCompany.name for carCompany in carCompanies">
<option value="">All Car Companies</option>
</select>
My Scenarios is:
For the first time, When categoryChanged is called, ng-include loads the template and user selects a carCompany $scope's property selectedCarCompany is set. But even if the user change the category from the dropdown and categoryChanged event changes the template to some other view, still $scope'sselectedCarCompany have the value from the previously selected template. Is there a way to clear the $scope on change of ng-include template?

Related

How pass select data from View to JS with Angular

I´m working in Angular and I have fields to fill like
I fill my select list as:
function cargarCatalogo() {
apiService.get("../../api/Catalogos/",
null,
function(res) {
//console.log(res.data);.
$scope.Catalogos = res.data;
$scope.selected = $scope.Catalogos[0];
},
errorCatalogo);
}
I want to know how can I pass selected Value into url in my funcion:
function actualizar(vehiculo) {
$scope.vehiculo.Origen = $scope.usuario.Origen;
$scope.vehiculo.Version = $scope.Version;
apiService.post("../../api/AddCatalogoRegistro/" + selected.ID,
function(res) {
// my code
How can I pass that selected value as a selected.ID, chrome console throw me
ReferenceError: selected is not defined
View:
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos">
<option></option>
</select>
Use $scope.selected as ng-model value
<select class="form-control" ng-change="filtro(selected)"
ng-init="Catalogos[0]" ng-model="selected"
ng-options="item.Nombre for item in Catalogos">
It should solve your problem. And the best practise is to name the controller and use ng-model = "ctrlName.selected"

Dropdown is not set with its ng-model Value in Edit-Profile Case

My Dropdown is not set with its ng-model Value in Edit-Profile Case
Here is my Controller.js method which calls service.js method and get data from database in Json format
function CountryList() {
var getUserData = crudAJService.CountryList(); // calls Service method
getUserData.then(function (response) {
$scope.countryList = response.data;
}, function () {
console.log("Can't read Country data");
});
I get countryList properly and html is rendered as expected (as I expect)
<select class="form-control ng-pristine ng-valid ng-valid-required ng-touched" name="country" required="" ng-model="countryid"
ng-options="option.Value as option.Text for option in countryList" ng-change="GetSelectedState(countryid)">
<option value="" class="" selected="selected">Choose Country</option>
<option value="1" label="India">India</option>
<option value="2" label="USA">USA</option>
<option value="3" label="China">China</option>
<option value="4" label="UK">UK</option>
<option value="5" label="Australia">Australia</option>
<option value="6" label="koria">koria</option>
<option value="7" label="Pakistan">Pakistan</option>
</select>
There is also ng-change Method for getting state from Db with respect to countryId (Cascading-Dropdown) which is also fetched smoothly and rendered properly.
but in Edit Profile case my dropdown is not set on ng-model value.?(not set selected value)..
if I bind {{countryid}} than it is also get proper result in my form(for testing purpose).
Here is my EditUser() method which is called when Edit button pressed from gridView.
$scope.EditUser = function (user) {
var getUserData = crudAJService.getUser(user.UserID);
getUserData.then(function (_user) {
CountryList(); //this method is mention above.
$scope.user = _user.data;
$scope.firstName = user.FirstName;
$scope.lastName = user.LastName;
$scope.countryid = user.CountryID;
Blah.. Blah.. So on
}, function () {
alert('Error in getting User records');
});
I think I had given all the necessary information with code. but still if You want any info plz tell me.
UPDATE
As you Suggest I make an object for ng-model and than I changed HTML Like this
<select class="form-control" name="country" required="" ng-model="countryModel" ng-options="countryModel.Value as countryModel.Text for countryModel in countryList" ng-change="GetSelectedState(countryModel.Value)">
now my controller.js EditUser() method is Looks Like this Image ..
(See Image.)
ng-model should be an object with two properties Value and Text. While ng-option is an array of objects. So in your case your countryList is like this:
$scope.countryList = [{Value: 1, Text: "India"}, {Value: 2, Text: "USA"}]
So countryid must be an object like this:
$scope.countryid = {Value: 1, Text: "India"}
UPDATE
If you only have country value then you can use this to build 'countryId' object:
let selectedId = 1;
$scope.countryId = $scope.countryList.filter(function (country) {
return country.Value == selectedId;
})[0];
Your HTML for select element will then become like this:
<select class="form-control" name="country" required="" ng-model="countryModel" ng-options="countryOpt as countryOpt.Text for countryOpt in countryList" ng-change="GetSelectedState(countryModel.Value)">

ng-model weird behavior with Asynchronous function

Below is drop down selection code :
<select ng-model="filter.area">
<option value="">Select your location</option>
<option ng-repeat="area in areaNames" value='{{ area.area_name }}'>{{ area.area_name }}</option>
</select>
ng-model is set in controller before Async function is called:
$scope.filter.area = $cookies['filterArea'];
// which evaluated to some value lets say 'Bole'
Now comes asynchronous function:
query.find({
success: function(results_area) {
$scope.$apply(function() {
$scope.areaNames = results_area;
for (var i = 0; i < $scope.areaNames.length; i++) {
$scope.areaNames[i].area_name = $scope.areaNames[i].get('name');
};
});
},
error: function(error) {
console.log("error in fetching area info....");
}
});
ng-model isn't updating. Any idea whats wrong here?
To see the demo go here :
http://peppy-avatar-762.appspot.com/
Then select "Addis Ababa" and Select "Bole" as area then click on find food! Check area filter on left side. ng-model doesn't get updated!
If the options are loaded lazily, use ng-options instead of using ng-repeat on option
<select data-ng-model="selectedItem"
data-ng-options="item for item in items track by item">
</select>
Working Plnkr

calling a HTTP get method to populate the result in drop down using angular JS

I have all controllers defined at one place.
$routeProvider.when(pages.hello,
{
templateUrl: 'test/hello.html',
controller: 'myController',
access: access.anon,
helloPage: 'arf'
});
My hello.html looks like this.
<select name="chooseFunc" data-ng-model="choosenFunction" class="input-xlarge ng-pristine ng-valid" data-ng-click="fetchID()" data-ng-change="update(choosenFunction)">
<option value="ABCD">ABCD</option>
<option value="CDEF">CDEF</option>
</select>
Now I want to call a http get method "/abc/hello" to populate the drop down like ABCD, CDEF values based on it.
I have written some thing like this.
$scope.fetchID = function() {
console.log("hello in fectch id");
$http.get('/abc/hello').success(successCallback).error(error);
};
My function is not getting called. Could some help me with the following.
Calling fecthID() function on page load.
fechID() function should populate the options in select element.
I am new here. Can some one help me.
I would write controller like:
function myController($scope,$http) {
$scope.values = [{id:"ABCD",Name:"David"},{id:"CDEF",Name:"John"}];
$scope.selectedItem = $scope.values[0].id;
$scope.fetchID = function() {
$http.get('/abc/hello').success(
function(data, status, headers, config){
$scope.values.push(data);// play here
})
.error(error);
};
$scope.fetchID(); // call
}
and hello.html with init first combo value:
<select name="chooseFunc"
ng-model="selectedItem"
ng-options="selectedItem.id as selectedItem.id for selectedItem in values"
class="input-xlarge ng-pristine ng-valid"
data-ng-click="fetchID()"
data-ng-change="update(choosenFunction)"
></select>
You can use ng-options to populate select like
<select ng-model="mySelecetdValue" ng-options="item for item in items">
</select>
To Call fecthID(), Just call it like
$scope.fetchID()
And Populate items in successCallback function

Dynamic select menu not working after change event

Im trying to make a dynamic select menu where you select a customer and then filter the contacts for that customer.
when i select a customer it properly filters the contacts but the customer select menu does not show that anything is selected.
<template name="newLeadForm">
<form id="lead">
<fieldset>
<legend>New Lead</legend>
<br/>
<select id="customer_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each customers}}<option id="{{id}}" value="{{_id}}">{{name}} - {{city}}, {{state}} {{zip}}</option>{{/each}}
</select>
<select id="contact_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each contacts}}<option id="{{id}}" value="{{_id}}">{{first_name}} {{last_name}}</option>{{/each}}
</select>
<input id="submit" type="submit" class="btn">
</fieldset>
</form>
</template>
Here is the data being supplied to the template
Template.newLeadForm.customers = function () {
return Customers.find();
};
Template.newLeadForm.contacts = function () {
console.log(Session.get("_customer_id"));
return Contacts.find({customer_id: Session.get("_customer_id")});
};
and the event handlers
Template.insert.events({
'change form#lead #customer_id' : function (event) {
customer = $("form#lead #customer_id").val();
Session.set("_customer_id", $("form#lead #customer_id").val());
},
'submit form#lead' : function (event) {
if (event.type === 'click' || event.type === 'submit') {
event.preventDefault();
var customer_id = $("#customer_id").val();
var contact_id = $("#contact_id").val();
var lead_source_id = $("#lead_source_id").val();
var lead_number = $("#lead_number").val();
if(Leads.insert({id: Leads.find().count() + 1, customer_id: customer_id, contact_id: contact_id})) {
$("#customer_id").val(null);
$("#contact_id").val(null);
Session.set("_customer_id", null);
}
}
}
});
After Meteor re-renders the option elements in your select element, you should tell it to set the selectedIndex property on the select element so that it updates. You can do this with the rendered event:
Template.newLeadForm.rendered = function() {
$("#customer_id")[0].selectedIndex = 5; // possibly track the index so you know what to set it to
}
Simple workaround:
Template.newLeadForm.rendered = function(){
$('#customer_id').val(Session.get("_customer_id"))
}
Since newLeadForm depends on Session["_customer_id"], it will be re-rendered whenever Session["syntax"] changes, and thus template.hello.rendered will be called every time Session["syntax"] changes.
Another option, you can add an autorun for each select you want to keep updated:
if (Meteor.isClient){
Meteor.startup(function() {
Deps.autorun(keep_cust_select_updated)
})
function keep_cust_select_updated(){
$('#customer_id').val(Session.get("_customer_id"))
}
}
Whenever the Session.set("_customer_id", xxxx) is called, keep_select_updated will be rerun (as it is dependent on Session.get("_customer_id")) and the correct value will be selected (by the jQuery $('#customer_id').val(...) call).
The advantage of the latter method is you don't need to bother adding "selected" correctly into the html for each <option>

Categories

Resources