$scope doesn't reflect ng-model - angularjs

The ng-model defined in a select-tag does not seem to affect the controller $scope-variable with the same name.
Controller:
.controller('AccountCtrl', function($scope, $state, User, apiUrls) {
$scope.enviroments = apiUrls;
$scope.updateEnviroment = function() {
console.log($scope.selectedEnv);
}
})
View:
<label class="item item-input item-select">
<div class="input-label">
Enviroment
</div>
<select ng-model="selectedEnv" ng-options="item as item.name for item in enviroments" ng-change="updateEnviroment()" ng-init="selectedEnv = enviroments[0]">
</select>
</label>
<p>{{selectedEnv}}</p>
And for clearity, the constant:
myApp.constant('apiUrls', [
{ "name": 'Production', "id": 1, "url": 'http://api.server.com/api/v1' },
{ "name": 'Developement', "id": 2, "url": 'http://apidev.server.com/api/v1' },
{ "name": 'Local', "id": 3, "url": 'http://localhost/CABApi/api/v1'}
]
);
console.log($scope.selectedEnv); => undefined (?)
Obviously something is not correct that I'm failing to recognize, any ideas?

Related

I am fetching data from a JSON file and displaying the list in my view(directory.php).But it's showing some error: order:notArray

If I am doing it by defining an array, it's all working fine.But the
issue occurs only when I try to fetch JSON data.
Below is my code for a file directory.php which I am later including with ng-view in my main index file using routing:
Order By Name
Order By Belt
<div class="content">
<button ng-click = "order = 'name' " >Order By Name</button>
<button ng-click = "order = 'belt' " >Order By Belt</button>
<input type="text" ng-model = "search" placeholder="Search for a ninja here...">
<ul>
<li ng-repeat = "ninja in ninjas |orderBy: order | filter: search" ng-show = "ninja.available">
<img ng-src = "{{ ninja.thumb }}" style="margin: -12px 10px 0 0; float: left; width: 55px" ng-show = "ninja.thumb" />
<h3>{{ ninja.name }} - {{ ninja.rate | currency}}</h3>
<div class="remove" ng-click = "removeNinja(ninja)">×</div>
<span class="belt" style="background: {{ ninja.belt }}">{{ ninja.belt }} belt</span> <hr><hr>
</li>
</ul>
<form ng-submit = "addNinja()">
<input type="text" placeholder="Enter ninja name here..." ng-model = "newninja.name">
<input type="text" placeholder="Enter ninja belt here..." ng-model = "newninja.belt">
<input type="text" placeholder="Enter ninja rate here..." ng-model = "newninja.rate">
<input type="submit" value="Add Ninja">
</form>
</div>
And in the module, I am using this code.The last section using $http.get()... is the concern here:
let myModule = angular.module('myModule',['ngRoute']);
myModule.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/home',{
templateUrl:'views/home.php'
})
.when('/directory',{
templateUrl:'views/directory.php',
controller:'MyController'
}).otherwise({
redirectTo:'/home'
});
}]);
myModule.controller('MyController',['$scope','$http',function($scope,$http) {
$scope.addNinja = function() {
$scope.ninjas.push({
name: $scope.newninja.name,
belt: $scope.newninja.belt,
rate: parseInt($scope.newninja.rate),
available: true
});
$scope.ninja.name = "";
$scope.ninja.belt = "";
$scope.ninja.rate = "";
}
$scope.message = "Here is the list of some ninjas below";
$scope.removeNinja = function(ninja) {
let removedNinja = $scope.ninjas.indexOf(ninja);
$scope.ninjas.splice(removedNinja,1);
}
$http.get('data/ninjas.json')
.then(function(data) {
$scope.ninjas = data;
},
function(error) {
console.log(error);
}
);
}]);
Below is the JSON file which contains the data:
[
{
"name": "Yoshi",
"belt": "green",
"rate": 50,
"available": true,
"thumb": "content/img/Yoshi.png"
},
{
"name": "Lee",
"belt": "black",
"rate": 100,
"available": true,
"thumb": "content/img/Lee.png"
},
{
"name": "Law",
"belt": "yellow",
"rate": 1000,
"available": true,
"thumb": "content/img/Law.png"
},
{
"name": "Jin",
"belt": "orange",
"rate": 300,
"available": false,
"thumb": "content/img/Jin.png"
}
]
if you receive a JSON object you must convert in into Object by angular.fromJson() method
try in this way
$http.get('data/ninjas.json')
.then(function(data) {
$scope.ninjas = angular.fromJson(data);
},
function(error) {
console.log(error);
}
);

Using angular ui-bootstrap and typeahead selection

I have a project where I am trying to use Typeahead (ui.bootstrap.typeahead) from http://angular-ui.github.io/bootstrap/
I have a select loading data options from a remote server(data1.json).
When the user type into select, I´d like to show on dropdown something with the format "Acrelandia - AC"(the format is cityname+' - ' +id), and the ng-model needs contain the next data:{city:'Acrelandia',state:'AC'}
Of course, The seleted text needs to be something as: "Acrelandia - AC"
I have tried the next but, I don´t know how format the result from promise to my requirements. It shows all cities in wrong format.
js:
data1:json:
{
"state": [
{
"id": "AC",
"name": "Acre",
"city": [
"Acrelandia",
"Assis Brasil",
"Brasileia",
]
},
{
"id": "AL",
"name": "Alagoas",
"city": [
"Agua Branca",
"Anadia",
"Vicosa"
]
}
]
}
js:
app.controller('infoController',['$scope','$http',function($scope,$http){
$scope.getLocation = function(val) {
return $http.get('/data1.json', {
params: {
address: val,
sensor: false
}
}).then(function(response){
return response.data.estados.map(function(item){
return item.cidades.toString();
});
});
};
Markup:
<div class="input-group ">
<input type="text" ng-model="customerCity" placeholder="Type something" uib-typeahead="address for address in getLocation($viewValue)" typeahead-loading="loadingLocations" typeahead-no-results="noResults" class="form-control">
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noResults">
<i class="glyphicon glyphicon-remove"></i> No Results found
</div>
</div>

eHow to create drop down (grouped) using ng-options?

I have json of all countries with me.
{"countries":[
{"name":"Afghanistan","code":"AF"},
{"name":"Åland Islands","code":"AX"},
{"name":"United States","code":"US"},
{"name":"Canada","code":"CA"},
{"name":"India","code":"IN"}
]};
I want to create drop down like
"
Choose Country(Default)
United States
Canada
------------
Åland Islands
Afghanistan
India
So on..."
I can be achieved via ng-repeat like
<select name="country" id="country" data-ng-model="country" required data-ng-change="allSelect()">
<option value="default" data-ng-data-ng-bind="'Choose Country'"></option>
<option value="{{cList.code}}" data-ng-if="cList.code === 'US'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="{{cList.code}}" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
<option value="default1">--------------------------------------------------</option>
<option value="{{cList.code}}" data-ng-if="cList.code !== 'US' && cList.code !== 'CA'" data-ng-repeat="cList in countries" data-ng-bind="cList.name"></option>
</select>
How can i do same via ng-options?
Currently if i want to select any option by default is not happening its creating blank string.
Country list and default values i am getting from different ajax call.
You need to make some changes to your JSON
JSON
{
"Collections": [{
"Name": "North America",
"Countries": [{
"Name": "United States",
"code": "US"
}, {
"Name": "Canada",
"code": "CA"
}
]
}, {
"Name": "Asia",
"Countries": [{
"Name": "India",
"value": "IN"
}
]
}]
}
HTML
<body ng-controller="dobController">
<div class="col-md-20">
<div id="main">
<form class="form-horizontal" role="form">
<label class="control-label col-md-2">Filter List:</label>
<div class="col-md-5">
<select ng-model='theModel' ng-change="display(theModel)">
<optgroup ng-repeat='group in collection' label="{{group.Name}}">
<option ng-repeat='veh in group.Countries' value='{{group.Name}}::{{veh.Name}}'>{{veh.Name}}</option>
</optgroup>
</select>
</div>
</form>
</div>
</div>
Controller
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope", "$http",
function($scope, $http) {
$http.get('test.json').then(function(response) {
$scope.collection = response.data.Collections;
console.log(response);
});
$scope.display = function(name) {
alert(name.split("::")[0] + "." + name.split("::")[1]);
}
}
]);
DEMO

In Angular how can you dynamically add an input to be applied once

I have searched the web and found no example. I wonder if someone could help.
I have two instances of a dropdown or maybe more and I want to apply the add input dynamically to only that form but it applies to everyone with that ng-model everywhere on the web page.
The code is here https://plnkr.co/edit/PPDYKjztPF528yli9FbN
HTML:
<div class="main-content__right" ng-controller="QuestionController">
<div ng-repeat="element in questionList">
<fieldset>
<div ng-repeat="choice in formOptionData track by $index">
<a class="remove-field remove u-pull-right" ng-click="remove()">Remove</a>
<input id="input{{choice.name}}" placeholder="{{choice.label}}" type="number" name="{{choice.name}}">
</div>
<div id="add-more" class="well">
<div class="field">
<div style="width:100%;" class="dropdown">
<select name="{{options.name}}" id="select" data-ng-model="selectedValue" data-ng-options="options as options.label for options in element.inputElement | orderBy:'label'" ng-change="onCategoryChange(selectedValue)">
<option value="" data-id="null" disabled="" selected="">Select an item...</option>
</select>
</div>
</div>
{{formData}}
</div>
</fieldset>
</div>
</div>
APP.js
var app = angular.module("cab", []);
app.controller('QuestionController', function($scope) {
$scope.formOptionData = [];
$scope.selectedValue = {};
$scope.questionList = [{
"sectionTitle": "Travel",
"inputType": "select",
"inputElement": [{
"label": "Public transport",
"name": "travelOutgoing",
"helpInfo": "include train journeys",
"type": "select"
}, {
"label": "Taxis",
"name": "travelOutgoing",
"type": "select"
}
]
},
{
"sectionTitle": "Leisure",
"title": "Enter the amount you spend on entertainment and leisure. Leave them blank if they don\"t apply to you.",
"inputType": "select",
"inputElement": [
{
"label": "Eating out",
"name": "leisureOutgoing",
"helpInfo": "Include coffees, teas and snacks",
"type": "select"
},
{
"label": "Going out",
"name": "leisureOutgoing",
"helpInfo": "Include drinks, taxis, admission charges",
"type": "select"
}
] }
];
$scope.onCategoryChange = function(selectedItem) {
this.formOptionData.push(selectedItem);
};
$scope.remove = function(element) {
this.formData.splice(element,1);
};
});

How to add multiple input box dynamically with dropdown in angularjs

I am having this problem which I can't find the solution to.
1) I have a dropdown list which the data is pull in from a json file
2) When the user selects a item I want to dynamically add a input box without a button.
Got a jQuery code but wanted to do it the angular way, but read that ng-Change is not the same as jquery .change?
Can anyone help or point me into the right direction of how to do this.
HTML
<div class="main-content__right" ng-controller="QuestionController">
<div ng-repeat="element in questionList">
<fieldset>
<div id="add-more" class="well">
<div class="field">
<div style="width:100%;" class="dropdown">
<select name="{{options.name}}" id="select" data-ng-model="formData"
data-ng-options="options as options.label for options in element.inputElement | orderBy:'label'"
ng-change="onCategoryChange(formData)">
<option value="" data-id="null" disabled="" selected="">Select an item...</option>
</select>
</div>
</div>
{{formData}}
</div>
</fieldset>
</div>
app.js
var app = angular.module("cab", []);
app.controller('QuestionController', function($scope) {
var $scope.formData = {};
$scope.questionList = [{
"sectionTitle": "Travel",
"subTitle": "How much do you spend on these items for your car?",
"inputType": "select",
"inputElement": [{
"label": "Public transport",
"name": "travelOutgoing",
"helpInfo": "include train journeys",
"type": "select"
}, {
"label": "Taxis",
"name": "travelOutgoing",
"type": "select"
}, {
"label": "Bicycle",
"name": "travelOutgoing",
"helpInfo": "general running costs such as repair or rental",
"type": "select"
}, {
"label": "Car rental",
"name": "travelOutgoing",
"helpInfo": "include fuel, parking charges and tolls",
"type": "select"
}
]
}];
$scope.onCategoryChange = function () {};
});
can be found on http://plnkr.co/edit/PPDYKjztPF528yli9FbN?p=preview
Your controller function needs to add each selection to an array on scope:
Controller
app.controller('QuestionController', function($scope) {
$scope.formData = [];
$scope.selectedValue = {};
$scope.questionList = [{
"sectionTitle": "Travel",
"subTitle": "How much do you spend on these items for your car?",
"inputType": "select",
"inputElement": [{
"label": "Public transport",
"name": "travelOutgoing",
"helpInfo": "include train journeys",
"type": "select"
}, {
"label": "Taxis",
"name": "travelOutgoing",
"type": "select"
}, {
"label": "Bicycle",
"name": "travelOutgoing",
"helpInfo": "general running costs such as repair or rental",
"type": "select"
}, {
"label": "Car rental",
"name": "travelOutgoing",
"helpInfo": "include fuel, parking charges and tolls",
"type": "select"
}]
}];
$scope.onCategoryChange = function(selectedItem) {
$scope.formData.push(selectedItem)
};
});
Then you can use an ng-repeat to render all of the items in formData.
HTML
<fieldset>
<div id="add-more" class="well">
<div class="field">
<div style="width:100%;" class="dropdown">
<select name="{{options.name}}" id="select" data-ng-model="selectedValue" data-ng-options="options as options.label for options in element.inputElement | orderBy:'label'" ng-change="onCategoryChange(selectedValue)">
<option value="" data-id="null" disabled="" selected="">Select an item...</option>
</select>
</div>
</div>
<div ng-repeat="item in formData track by $index">
<input ng-model="item.label" />
</div>
</div>
</fieldset>

Resources