Angular - Data Bind Issue - angularjs

So the main functionality I want is here, which is selecting an option from the drop-down menu and having it populate my input field.
JSFiddle:
<div ng-app="app" ng-controller="MainCtrl">
Two things I want to fix:
When typing into the input ("Email Subject") field I don't wan't it to change the drop-down menu option.
I want the input field to initialize with it's placeholder value of ("Email Subject") instead of initializing with "Select a Canned Response"
I'm assuming this means making the input field have a one-way data bind, but I'm not sure how to do this, any help is appreciated.

<div ng-app="app" ng-controller="MainCtrl">
<input ng-model="CannedResponse" placeholder="Email Subject"><!--change this-->
<div class="item item-input item-select" >
<div class="input-label"> </div>
<select ng-model="newSelectedITem" ng-options="CannedResponse as CannedResponse.label for CannedResponse in CannedResponses"
ng-change="yourFunction()"> <!--change this-->
<option value="{{item.value}}"> </option>
</select>
</div>
</div>
js code
angular.module('app', [])
.controller('MainCtrl', function($scope) {
$scope.CannedResponses = [{
label: 'Selet a Canned Response',
value: 0
}, {
label: 'Hi there whats up',
value: 1
}, {
label: 'Here is another response',
value: 2
}, {
label: 'Why not select this one?',
value: 3
}];
$scope.newSelectedITem = $scope.CannedResponses[0] //ADD THIS (X1)
$scope.CannedResponse='';//add this
$scope.yourFunction = function() {//add this function
$scope.CannedResponse = $scope.newSelectedITem.label;
};
});
see where I wrote change this. There where you have to change your code.

Related

AngularJS Select Default Option from Select when user input changes

This question is specific to AngularJS 1.6.5 and above and does not apply to any previous versions.
I have a form with some ng-options selects and some text inputs. When a user selects the None / Custom option, a text input appears to the right. Once the user starts typing in that input, the None / Custom option is deselected and a new unknown option is added.
This is the result of a bug fix introduced in AngularJS 1.6.5. Previously when the user typed in the input, the None / Custom select remained selected.
My question is: how can I recreate the original pre-1.6.5 behavior?
To see an example of what I am talking about, check out these two fiddles. The first fiddle demonstrates the original behavior, the second demonstrates the current (undesired) behavior. Simply select the None / Custom option and type something in the adjacent text input.
Example Fiddles
AngularJS 1.6.4 example (good)
AngularJS 1.6.5 example (bad)
HTML code:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.min.js" type="text/javascript"></script>
</head>
<body ng-app="myapp">
<div class="wrapper" ng-controller="someCtrl">
<div class="row" ng-repeat="t in utmTags">
<div class="col-xs-1"><label style="color:#666;">{{t}}</label></div>
<div class="col-xs-2">
<select class="form-control flat inline-dropdown skinny" ng-options="o.value as o.key for o in utmOptions" ng-model="company[t]">
<option ng-value="company[t]" label="None / Custom"></option>
</select>
</div>
<div class="col-xs-2">
<input type="text" class="form-control flat skinny" style="width:180px;" placeholder="Add tag, without spaces" ng-if="!utmVariables.includes(company[t])" ng-model="company[t]" ng-pattern="utmRegex" />
<div ng-if="utmVariables.includes(company[t])">e.g. {{utmOptionsExamples[company[t]]}}</div>
</div>
</div>
</div>
</body>
</html>
Javascript Code:
var app = angular.module('myapp', ['ui.bootstrap']);
app.controller('someCtrl', ['$scope', function($scope) {
$scope.utmOptions = [
{ key: '{AmbassadorFirstNameLastInitialID}', value: '{AmbassadorFirstNameLastInitialID}' },
{ key: '{AdminFirstNameLastInitial}', value: '{AdminFirstNameLastInitial}' },
{ key: '{ContentDomain}', value: '{ContentDomain}' },
{ key: '{ShareDate}', value: '{ShareDate}' },
{ key: '{ShareID}', value: '{ShareID}' },
{ key: '{SocialPlatform}', value: '{SocialPlatform}' }
];
$scope.utmOptionsExamples = {
'{AmbassadorFirstNameLastInitialID}': 'TracJ-1318',
'{AdminFirstNameLastInitial}': 'ShanA',
'{ContentDomain}': 'entrepreneur.com',
'{ShareDate}': '2017-08-23',
'{ShareID}': '79131',
'{SocialPlatform}': 'Twitter'
};
$scope.utmRegex = /^[a-z0-9\-\._]*[\{\}]{0}$|^{[a-z0-9\-\._]*}$/i;
$scope.utmTags = ['utm_medium', 'utm_source', 'utm_campaign', 'utm_term', 'utm_content'];
$scope.utmVariables = ['{AmbassadorFirstNameLastInitialID}', '{AdminFirstNameLastInitial}', '{ContentDomain}', '{ShareDate}', '{ShareID}', '{SocialPlatform}'];
$scope.company = {
utm_medium: undefined,
utm_source: undefined,
utm_campaign: undefined,
utm_term: undefined,
utm_content: undefined
}
}]);
app.run();

Select changes do not affect ng-model

I've been having a look some related post with no success in my case even having the same code.
I have a select like the following:
<div class="form-group">
<label for="col">Visible: </label>
<select class="custom-select" id="col"
ng-options="visible as visible.name for visible in visibility"
ng-model="selected_visible_product"
ng-change="update_product_list()"
style="width:140px">
<option>Visibility...</option>
</select>
<label>{{selected_visible_product}}</label>
</div>
Visibility array is defined like this:
$scope.visibility = [{ID:0, name:'Disabled'},{ID:1, name:'Enabled'}];
First time a print the value of selected_visible_product, it shows the correct value, but when I change the select option, update_product_list() print again the actual value of selected_visible_product and it shows the same.
This is what update_product_list() prints (na matter what you choose):
Object {ID: 0, name: "Disabled", $$hashKey: "object:140"}
update_product_list() just print in console the value of selected_visible_product
$scope.update_product_list = function() {
console.info($scope.selected_visible_product.ID);
}
What's happening?
UPDATE:
Here is a working snippet with your code. It seems to be working fine. What's different?
angular.module('myapp', [])
.controller('mycontroller', ['$scope', function mycontroller($scope) {
$scope.visibility = [{ID:0, name:'Disabled'},{ID:1, name:'Enabled'}];
$scope.update_product_list = function() {
alert($scope.selected_visible_product.name);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycontroller">
<div class="form-group">
<label for="col">Visible: </label>
<select class="custom-select" id="col"
ng-options="visible as visible.name for visible in visibility"
ng-model="selected_visible_product"
ng-change="update_product_list()"
style="width:140px">
<option>Visibility...</option>
</select>
</div>
</div>

Update value of an input text when an option is selected with angularjs

I have my controller in angularjs with a array
app.controller('player', function($scope) {
$scope.players = [
{
"id":3,
"name":"Nadal",
},
{
"id":4,
"name":"Federer"
}
]
});
In my HTML I have HTML with a dropdown and a textbox.
<html ng-app="pdl">
<body ng-controller="player">
<input type="text" id="name" value=""/>
<select name="id">
<option ng-repeat="player in players" value="{{player.id}}">{{player.id}}</option>
</select>
</body>
</html>
I want to update the input with a 'name' when I choose an option from the dropdown
Bind both select and input to the same ngModel:
angular.module('pdl', []).controller('player', function($scope) {
$scope.players = [{
"id": 3,
"name": "Nadal",
}, {
"id": 4,
"name": "Federer"
}]
});
<script src="https://code.angularjs.org/1.5.5/angular.min.js"></script>
<div ng-app="pdl" ng-controller="player">
<input type="text" ng-model="player.name" />
<select ng-model="player" ng-options="player as player.name for player in players">
</select>
</div>
And use ngOptions for selectbox.
The solution above works, but breaks if you want to amend the input value after its been written. In the example above change the word Nadal and the select is changed also as they are bound to the same value.
If want to amend the value of the input and you don't want to bind to the same ngModel, you could use ng-change on the select, and pass it the value you want to display in the input.
In this example I insert the "ng-change" statement on the select...
ng-change="change(model.action)"
and in the controller I update the scope for the input
$scope.change = function (str) {
$scope.model.action = str;
};
Every time you update the select the input will update too, but you can amend the input value without touching the select as they are bound differently.

how to bind .json file to auto complete drop down list in MVC AngularJS

I'm having large data of city names in .json file, i want to bind that all city names to my auto complete drop down list by using Mvc AngularJS so is there any way to do that,thanks in advance
https://github.com/ghiden/angucomplete-alt
You can make use of this plugin I think. Here's how you can use it.
<angucomplete-alt id="members"
placeholder="Search members"
pause="400"
selected-object="selectedCity"
remote-url="http://myserver.com/api/user/find?s="
remote-url-data-field="results"
title-field="name"
input-class="form-control form-control-small"/>
On server side you will receive the typed string as GET parameter.
Request.QueryString["type"];
Your server function should return the result in following JSON format.
{
results : [{'name': 'first city', 'name': 'second city'}]
}
2nd Option
In case you have to stick with static json file then you can use following approach as well. This will also work fast as all cities and loaded once and then filtering happens locally.
In Template
<div angucomplete-alt id="ex1"
placeholder="Search cities"
maxlength="50"
pause="100"
selected-object="selectedCity"
local-data="cities"
search-fields="name"
title-field="name"
minlength="1"
input-class="form-control form-control-small"
match-class="highlight">
</div>
then in your controller add this. This loads your json file into cities array which is used by the directive for auto complte purpose
$scope.cities = [];
$http.get('http://server/cities.json')..success(function(response) {
$scope.cities = response.data;
});
ng-options="color.Name for color in Colors"
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Colors = [{
Id: 1,
Name: 'Red'
}, {
Id: 2,
Name: 'Blue'
}, {
Id: 3,
Name: 'Green'
}];
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<select ng-model="ddlColors" ng-options="color.Name for color in Colors track by color.Id">
</select>
</div>
Controller code
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.Fruits = [{
Id: 1,
Name: 'Apple'
}, {
Id: 2,
Name: 'Mango'
}, {
Id: 3,
Name: 'Orange'
}];
});
HTML Code
<label class="item item-input item-select">
<div class="input-label" style="color:#387ef5;">
Type of call :
</div>
<select name="fruitType" class="form-control" ng-change="getSectedTypeValue(selectedID)" ng-model="selectedID" ng-options=" fruitType as fruitType.Name for fruitType in Fruits track by fruitType.Id" value="{{fruitType.Id}}" required>
<option value=""> Select Call Type </option>
</select>
</label>

Passing values to ng-model from ng-repeat

I have a form that passes its inputs to ng-model before storing to the database. One of which is a dynamic value (pre-generated code) that is taken from its database table.
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1">
<input class="form-control" type="text" name="code" ng-model="formData.code" ng-value="codes.code" readonly="" />
</div>
Theoretically, once the ng-model gets the value, it then passes it to the insert call for the database to store it along with the rest of the fields.
scope.processForm = function(isValid){
scope.$submitted = true;
if(isValid && state.$current=='registration.signupapp') {
http.post("server/insert.php",{'code': scope.codes.code, 'fullname': scope.formData.name, 'instagram': scope.formData.igname, 'email': scope.formData.email, 'mobile': scope.formData.mobile, 'location': scope.formData.location.type, 'branch': scope.formData.branches.branch}).success(function(data, status, headers, config){
console.log("inserted successfully");
});
state.go('registration.success');
} else if(!isValid) {
//alert("Please make sure that you entered everything correctly.");
}
};
Unfortunately, this does not work. 1) I was told that you cannot simply pass an ng-value to an ng-model inside an input[text]. 2) Even if in the case that the value is passed to ng-model, I am not sure what to call inside the controller as scope.codes.code nor scope.formData.code do not seem to work and gets either a not defined error or 404.
In a nutshell, how do I:
Get the value generated by ng-repeat as set to limitTo:1.
Store it to ng-model in real-time (as this is very dependent on a
dynamic dropdown).
Pass the value of ng-model back to the controller.
Send it back to the server and store it to the database.
I guess ng-init should help you out here.
Change your code segment from:
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1">
<input class="form-control" type="text" name="code" ng-model="formData.code" ng-value="codes.code" readonly="" />
</div>
to:
<div class="form-group" ng-repeat="codes in response | filter: {branch: formData.branches.alias, taken: 0} | limitTo: 1" ng-init="formData.code=codes.code">
<input class="form-control" type="text" name="code" ng-model="formData.code" readonly="" />
</div>
This is really contrived, but here's a very simplified demo:
var app = angular.module('demo', []);
app.filter('myFilter', function(){
return function(data){
return data[0];
};
});
app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter){
var myfilter = $filter('myFilter');
$scope.response = ['001', '002', '003', '004', '005'];
$scope.items = ['Item 1', 'Item 2', 'Item 3']
$scope.formData = {};
$scope.$watch('formData.select', function(newval){
if (newval === 'Item 1') {
$scope.formData.code = myfilter($scope.response);
} else {
$scope.formData.code = '';
}
});
}]);
#import "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css";
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="demo" ng-controller="MainCtrl">
<pre>formData.code = {{formData.code || "No Code for this Item"}}</pre>
<div class="form-group">
<label>Select a Value: <em>Choose Item 1 to update formData.code</em></label>
<select class="form-control" ng-model="formData.select" ng-options="item as item for item in items"></select>
</div>
<div class="form-group">
<label>formData.code:</label>
<input class="form-control" type="text" name="code" ng-model="formData.code" />
</div>
</div>
You have the response already, so rather than use ng-repeat, just add the value to the formData.code on the controller. If you need to use a custom filter, you can pass in the $filter service as a dependency to your controller.
Edit:
I didn't notice the part about the formData.code being dependent on another form value, so I updated the demo to include a $watch function.

Resources