ng-model value not passed to the controller function - angularjs

I am using ng-model to pass the form value to a controller function. But it is not passing correct values of the check boxes. Here is my plunker. Please help me out with this.
https://plnkr.co/edit/3gOuQwzt3SMNbAXplq0x?p=preview
My template is:
<div class="tab-pane fade " ng-repeat="(key, value) in all_user_wl_data" id="{{key}}" ng-class='{"in active":$first}'>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-md-6 col-lg-6" ng-repeat="(key1, value1) in value.wl_dict">
<div class="checkbox checkbox-success">
<input id="{{key1}}" type="checkbox" name="valueis" class="form-control" ng-model="formData[key1]">
<label for="{{key1}}">
{{value1}}
</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="row"><div class="col-lg-3 col-md-3 col-sm-3"> <label class="control-label">Group Name </label></div>
<div class="col-md-6 col-sm-6 col-lg-6"> <input type="text" name="regular" class="form-control" ng-model="formData.key2"></div></div><br>
<button type="button" class="btn btn-success" data-original-title="" title="" ng-click="createGroup(formData)">Save changes</button>
</div>
Here when I print console.log(formData), it prints only the value of text box and doesn't prints checkbox value.

try this. in controller define $scope.formData = [];

You didn't initiate $scope for checkbox ng-model "formData" ..
So if you initiate model into controller like this , $scope.formData = []
It will append true value in your formData like this,
[2221: true, 8233: true]

As everyone suggested.
Set $scope.formData in controller
Working plnkr
use
$scope.formData = {}
in your controller
https://plnkr.co/edit/53YVnVyOQzqxHQIPshkq?p=preview

I changed your script to below and it works
angular.module('formExample', []) .controller('ExampleController', ['$scope', '$http', function($scope, $http) {
$scope.formData = {};
$http.get('test.json')
.success(function(data) {
$scope.all_user_wl_data = data;
angular.forEach(data, function(areadata) {
$scope.usersubscribedwl = data;
console.log(data);
})
})
$scope.createGroup = function() {
console.log($scope.formData);
}
}

try this
<input id="{{key1}}" type="checkbox" name="valueis" class="form-control" ng-model="formData.key1[value1]">
and in controller
$scope.formData=[];
https://plnkr.co/

Related

angularjs dynamic form field inside ng-repeat

Hi I have problem in adding form field and binding inside the ng-repeat
my form is like this
<div ng-repeat="(key, value) in categories">
<div class="col-sm-12"><b>{{ value.name }}</b></div>
<div class="col-sm-12" >
<div class="col-sm-3">
<label>Product</label>
<input
type="text"
class="form-control input-sm"
ng-model="product.name">
</div>
<div class="col-sm-1">
<label> </label>
<button type="button" ng-hide="$first" ng-click="removeProduct()">-</button>
</div>
</div>
<div class="col-sm-1">
<button type="button" ng-click="addNewProduct()">+</button>
</div>
</div>
json categories
[{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"},
{"id":3,"name":"Office Equipment"},
{"id":4,"name":"Renovation"},
{"id":5,"name":"Vehicle"}]
Here I want to add dynamic form fields(products) for each category
my js is like this
$scope.addNewProduct = function(){
$scope.categories.push({});
}
$scope.removeProduct= function(index){
$scope.categories.splice(index,1);
}
i know its won't work i need to push data to each category.please help
Your function for adding new category should look like this:
$scope.addNewProduct = function(){
var newCategory=
{
id:$scope.categories.length+1,
name:$scope.product.name
}
$scope.categories.push(newCategory);
}
Following code will demo how to append 'item' to items list:
<script>
angular.module('AddItemToList', [])
.controller('FormController', ['$scope', function($scope) {
$scope.item = '';
$scope.items = [];
$scope.submit = function() {
if (typeof($scope.item) != "undefined" && $scope.item != "") {
// append item to items and reset item
$scope.items.push($scope.item);
$scope.item = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="FormController">
Input item and Submit the form. This will get appended to the list:
<input type="text" ng-model="input" name="item" />
<input type="submit" id="submit" value="Submit" />
<pre>Final List={{items}}</pre>
</form>

angularjs scope within scope dynamic elements saving

I am having quite the trouble with scopes created by directives, and saving these dynamic elements' scope back to the parent.
Here is my directive:
app.directive('action', function() {
return {
restrict: "E",
scope: {},
templateUrl:'views/pages/projects/triggers/newaction.html',
controller: function($rootScope, $scope, $element) {
$scope.groups = $scope.$parent.groups;
$scope.scenes = $scope.$parent.scenes;
$scope.actions = $scope.$parent.actions;
$scope.Delete = function(e) {
//remove element and also destoy the scope that element
$element.remove();
$scope.$destroy();
};
}
};
});
here is my controller:
.controller('NewTriggerCtrl', ['Auth', '$scope', 'toastr', '$state', '$stateParams', 'FBURL', '$filter', '$compile',
function(Auth, $scope, toastr, $state, $stateParams, FBURL, $filter, $compile) {
var authData = Auth.$getAuth();
var ref = new Firebase(FBURL + '/projects/' + authData.uid + '/' + $stateParams.projectid);
// Submit operation
var retriveActions = function() {
// http://stackoverflow.com/questions/12649080/get-to-get-all-child-scopes-in-angularjs-given-the-parent-scope
var theseactions = [];
var ChildHeads = [$scope.$$childHead];
var currentScope;
while (ChildHeads.length) {
currentScope = ChildHeads.shift();
while (currentScope) {
/* theseactions.push({
type: currentScope.type,
data: currentScope.data,
data2: currentScope.data2
}); */
console.log("currentscope.type = " + currentScope.type);
};
currentScope = currentScope.$$nextSibling;
}
//return theseactions;
};
var retrieveactions2 = function() {
var theseactions = [];
var newevent = null;
var newdata = null;
var newdata2 = null;
console.log("in retrieve actions");
angular.forEach(angular.element(document.getElementsByClassName("newaction")), function(element){
console.log("iterating");
newevent = $(this).find('.newactionevent').value;
newdata = $(this).find('.newactiondata').value;
newdata2 = $(this).find('.newactiondata2').value;
theseactions.push({
event: newevent,
data: newdata,
data2: newdata2
});
});
return theseactions;
}
$scope.ok = function(actions) {
//console.log(retriveActions(actions));
//retriveActions(actions);
//console.log("$scope.trigger.actions = " + $scope.trigger.actions);
//console.log("actions = " + actions);
console.log(retrieveactions2());
$scope.triggers.$add($scope.trigger).then(function (triggerRef) {
ref.child('triggers').child(triggerRef.key())
.update({created_at: Firebase.ServerValue.TIMESTAMP});
toastr.success('Trigger Added!', 'Trigger has been created');
$state.go('app.projects.edit', {projectid : $stateParams.projectid}, {reload: true});
});
};
$scope.newaction = function() {
var divElement = angular.element(document.querySelector('#actions'));
var appendHtml = $compile('<action></action>')($scope);
divElement.append(appendHtml);
};
$scope.cancel = function() {
$state.go('app.projects.edit', {projectid : $stateParams.projectid}, {reload: true});
};
/////////////////////// *Submit operation
}])
here is my new trigger html:
<div class="page page-newtrigger" ng-controller="NewTriggerCtrl">
<!-- row -->
<div class="row">
<div class="col-md-12">
<!-- tile -->
<section class="tile tile-simple">
<!-- tile body -->
<div class="tile-body">
<form name="form" class="form-horizontal form-validation" role="form" novalidate>
<div class="form-group mt-12" style="margin-top: 15px;">
<label for="name" class="col-sm-1 control-label">Name <span class="text-danger" style="font-size: 15px;">*</span></label>
<div class="col-sm-1">
<input type="text" name="name" class="form-control" id="name" placeholder="Trigger name..." ng-model="trigger.name" required>
</div>
<div class="btn-group col-sm-2">
<label class="btn btn-green" ng-model="trigger.type" uib-btn-radio="'astro'">Astro</label>
<label class="btn btn-green" ng-model="trigger.type" uib-btn-radio="'time'">Real-Time</label>
<label class="btn btn-green" ng-model="trigger.type" uib-btn-radio="'input'">Input</label>
</div>
<div class="animate-switch-container" ng-switch on="trigger.type">
<div class="animate-switch" ng-switch-when="astro">
<div class="btn-group col-sm-2">
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'sunrise'">Sunrise</label>
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'sunset'">Sunset</label>
</div>
<div class="col-sm-1">
<input type="text" name="offset" class="form-control" id="offset" placeholder="Offset (+/- minutes)" ng-model="trigger.option">
</div>
</div>
<div class="animate-switch" ng-switch-when="time">
<div class="btn-group col-sm-2">
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'repeat'">Repeat</label>
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'once'">Once</label>
</div>
<div class="animate-switch-container" ng-switch on="trigger.event">
<div class="animate-switch" ng-switch-when="repeat">
<div class="col-sm-3 btn-group">
<label class="btn btn-cyan" ng-model="trigger.option.mon" uib-btn-checkbox>Mon</label>
<label class="btn btn-cyan" ng-model="trigger.option.tue" uib-btn-checkbox>Tue</label>
<label class="btn btn-cyan" ng-model="trigger.option.wed" uib-btn-checkbox>Wed</label>
<label class="btn btn-cyan" ng-model="trigger.option.thu" uib-btn-checkbox>Thur</label>
<label class="btn btn-cyan" ng-model="trigger.option.fri" uib-btn-checkbox>Fri</label>
<label class="btn btn-cyan" ng-model="trigger.option.sat" uib-btn-checkbox>Sat</label>
<label class="btn btn-cyan" ng-model="trigger.option.sun" uib-btn-checkbox>Sun</label>
</div>
<div class="col-sm-1">
<input type="text" name="time" class="form-control" id="time" placeholder="Time (HH:mm:ss)" ng-model="trigger.data">
</div>
</div>
<div class="animate-switch" ng-switch-when="once">
<div class="col-sm-2" >
<p class="input-group" ng-controller="DatepickerDemoCtrl">
<input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="trigger.option" is-open="opened" min-date="minDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" ng-required="true" close-text="Close" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="fa fa-calendar"></i></button>
</span>
</p>
</div>
<div class="col-sm-1">
<input type="text" name="time" class="form-control" id="time" placeholder="Time (HH:mm:ss)" ng-model="trigger.data">
</div>
</div>
</div>
</div>
<div class="animate-switch" ng-switch-when="input">
<div class="col-sm-1">
<select ng-init="1" ng-model="trigger.option" class="form-control mb-10">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<div class="col-sm-2">
<div class="btn-group">
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'high'">Goes high</label>
<label class="btn btn-green" ng-model="trigger.event" uib-btn-radio="'low'">Goes low</label>
</div>
</div>
</div>
</div>
<button class="btn btn-success b-0 pull-right" style="margin-right: 30px;" ng-click="newaction()"><i class="fa fa-plus mr-5"></i>New Action</button>
</div>
<div id="actions">
<action ng-repeat="action in trigger.actions"></action>
</div>
<div class="form-footer">
<button class="btn btn-success b-0 pull-right" ng-click="ok(trigger)" ng-disabled="form.$invalid">Submit</button>
<button class="btn btn-lightred btn-ef btn-ef-4 btn-ef-4c" ng-click="cancel()"><i class="fa fa-arrow-left"></i> Cancel</button>
</div>
</form>
</div>
<!-- /tile body -->
</section>
<!-- /tile -->
</div>
</div>
<!-- /row -->
</div>
here is my newaction html:
<!-- row -->
<div class="newaction row">
<div class="col-md-10 col-sm-offset-2">
<form name="form" class="form-horizontal form-validation" role="form" novalidate>
<div class="form-group mt-12" style="margin-top: 15px;">
<div class="col-sm-1"><button ng-click="Delete($event)" class="btn btn-danger"><i class="glyphicon glyphicon-trash"></i></button></div>
<div class="btn-group col-sm-2">
<select ng-init="1" ng-model="action.type" class="newactiontype form-control mb-10">
<option value="transition-scene">Transition Scene</option>
<option value="set-group-intensity">Set Group Intensity</option>
<option value="inject-trigger">Inject Trigger</option>
<option value="color-change">Color Change</option>
</select>
</div>
<div ng-if="action.type=='transition-scene'">
<div class="col-sm-3">
<select chosen="" class="newactionevent form-control mb-10" ng-options="scene.name for scene in scenes track by scene.name" ng-model="action.scene"></select>
</div>
<div class="col-sm-1">
<input type="text" name="fadetime" class="newactiondata form-control" id="fadetime" placeholder="Fade Time (seconds)" ng-model="action.fadetime">
</div>
</div>
<div ng-if="action.type=='set-group-intensity'">
<div class="col-sm-3">
<select multiple chosen="" class="newactionevent form-control mb-10" ng-options="group.name for group in groups track by group.name | filter: {type : 'white'}" ng-model="$parent.action.group"></select>
</div>
<div class="col-sm-1">
<input type="text" name="intensity" class="newactiondata form-control" id="intensity" placeholder="Intensity(%)" ng-model="action.intensity">
</div>
<div class="col-sm-1">
<input type="text" name="fadetime" class="newactiondata2 form-control" id="fadetime" placeholder="Fade Time (sec)" ng-model="action.fadetime">
</div>
</div>
<div ng-if="action.type=='inject-trigger'">
<div class="col-sm-2">
<input type="text" name="triggernumber" class="newactiondata form-control" id="triggernumber" placeholder="Trigger number..." ng-model="action.data">
</div>
</div>
<div ng-if="action.type=='color-change'">
<div class="col-sm-3">
<select multiple chosen="" class="newactionevent form-control mb-10" ng-options="group.name for group in groups track by group.name| filter:group.type!='white'" ng-model="action.group"></select>
</div>
<div class="col-sm-1">
<input colorpicker="rgb" ng-model="action.data" type="text" class="newactiondata form-control w-md mb-10">
</div>
<div class="col-sm-1">
<input type="text" name="fadetime" class="newactiondata2 form-control" id="fadetime" placeholder="Fade Time (sec)" ng-model="action.fadetime">
</div>
</div>
</div>
</form>
</div>
</div>
<!-- /row -->
I have multiple attempts at this, as you can see with the two different functions in NewTriggerCtrl. The first was to get all the child scopes and iterate through, however when I call this it locks the browser up with over 250,000 logs. So maybe I am passing the wrong scope?
I am relatively new to Angular, and have some experience in JQuery, and I attempted to name the inputs with classes and finding them with document calls, but that is not working either. I have an app running and I can create, detele, etc. groups, triggers (not the trigger actions), and scenes, So I understand the basics of controllers and scopes. But saving these child scopes to the main trigger (what I assume would be trigger.actions) has stumped me. Maybe there is a better way to this? I know my code may not be efficient, I am attempting to get a base then clean up later.
Thank you.
UPDATE:
Ok so new directive:
app.directive('action', function() {
return {
restrict: "E",
scope: true,
templateUrl:'views/pages/projects/triggers/newaction.html',
controller: function($rootScope, $scope, $element) {
$scope.Delete = function(e) {
console.log("$scope.action = " + $scope.action);
//remove element and also destoy the scope that element
$element.remove();
$scope.$destroy();
};
}
};
});
and entire trigger controller:
'use strict';
app
.controller('TriggersCtrl', ['Auth', '$scope', '$state', '$stateParams', '$firebaseArray', '$firebaseObject', 'FBURL',
function(Auth, $scope, $state, $stateParams, $firebaseArray, $firebaseObject, FBURL) {
// General database variable
var authData = Auth.$getAuth();
var ref = new Firebase(FBURL + '/projects/' + authData.uid + '/' + $stateParams.projectid);
$scope.triggers = $firebaseArray(ref.child('triggers'));
$scope.groups = $firebaseArray(ref.child('groups'));
$scope.scenes = $firebaseArray(ref.child('scenes'));
$scope.triggersObject = $firebaseObject(ref.child('triggers'));
//////////////////////////// *General database variable
// get the model
if($stateParams.triggerid) {
var id = $stateParams.triggerid;
$scope.trigger = $firebaseObject(ref.child('triggers').child(id));
$scope.actionsObject = $firebaseObject(ref.child('triggers').child(id).child('actions'));
} else {
$scope.trigger = {};
$scope.actionsObject = {};
}
}])
.controller('NewTriggerCtrl', ['Auth', '$scope', 'toastr', '$state', '$stateParams', 'FBURL', '$filter', '$compile', '$firebaseArray',
function(Auth, $scope, toastr, $state, $stateParams, FBURL, $filter, $compile, $firebaseArray) {
var authData = Auth.$getAuth();
var ref = new Firebase(FBURL + '/projects/' + authData.uid + '/' + $stateParams.projectid);
// Submit operation
$scope.ok = function() {
console.log("$scope.actions = " + $scope.actions);
console.log("$scope.trigger.actions = " + $scope.trigger.actions);
$scope.triggers.$add($scope.trigger).then(function (triggerRef) {
ref.child('triggers').child(triggerRef.key())
.update({created_at: Firebase.ServerValue.TIMESTAMP});
toastr.success('Trigger Added!', 'Trigger has been created');
$state.go('app.projects.edit', {projectid : $stateParams.projectid}, {reload: true});
});
};
$scope.newaction = function() {
var divElement = angular.element(document.querySelector('#actions'));
var appendHtml = $compile('<action></action>')($scope);
divElement.append(appendHtml);
};
$scope.cancel = function() {
$state.go('app.projects.edit', {projectid : $stateParams.projectid}, {reload: true});
};
/////////////////////// *Submit operation
}]);
The scopes for the actions are created, and when i delete they are logged as an object. But the actions are not saved into trigger. I tried creating an actionsObject and then ng-repeat="action in actionsObject" but that didnt work. I try $scope.trigger.actions = $scope.actionsObject (to no avail) [my thought is how I created the $scope.trigger and the $scope.actionsObject is that they should behave the same if I call "action in actionsObject" vs "action in trigger.actions"..?]. My assumption is that I append the newaction template, which it's scope is action, the ng-repeat="action in trigger.actions" part, does this create the bind for when I add the new element to #actions that it saved to the trigger.actions scope? Having "scope: true" in the directive gives me the scenes and groups perfectly (understand the inheritance a little better). I should note that I create a trigger (a single one) and add multiple actions (which groups and scenes are part of the ng-options which is why i needed those models). Does the multiple appends affect anything? This is my last major feature to work out. I appreciate the help!
Your action directive use an isolate scope, and that is for internal use by the directive only.
The data you want to save in your Actions-array (to be submitted with the form) should go directly into the action-object and not on the scope.
You can access the action-object in two ways:
Use a child scope (by specifying scope: true instead of scope: {})
This allows you to access the parent's scope variables by inheritance:
$scope.action refers to the current action object (from ng-repeat)
$scope.groups refers to the groups array from the parent scope
This means you can assign data to $scope.action.something and it will affect the action object immediately. This is the beauty of angular: Manipulate the data directly, and skip the tedious "loop through everything to get the values".
You can also use an isolate scope (using scope: {} syntax). When using an isolate scope you need to specify explicitly the variables you want to use.
{
...
scope: {
theActionObject: '=',
groupList: '=',
sceneList: '='
}
...
}
This can then be referenced in you directive's link or controller function as $scope.theActionObject.
$scope.theActionObject.something = 'test';
// Access the groups array
alert($scope.groupList.length);
And to tie it together you need to specify the references in the HTML:
<div id="actions">
<action ng-repeat="action in trigger.actions"
the-action-object="action"
group-list="groups"
scene-list="scenes"></action>
</div>
Hope this will help you!
where are your groups, scenes and actions objects defined on the $parent scope? You would need to define them in your NewTriggerCtrl
$scope.groups = [];
$scope.scenes = [];
$scope.actions = [];
Since you are isolating scope, you would normally bind them through attributes like:
scope: {groups: '=', scenes: '=', actions: '=' }
and
<action ng-repeat="action in trigger.actions" groups="groups" scenes="scenes" actions="actions"></action>
An alternative to isolate scope would be to use a prototypical inherited scope with scope: true
Either way, binding $scope.foo = $scope.$parent.foo; seems unnecessary.
Those two methods are for if you actually need new scopes for each action directive. If you don't, then you can just leave the scope property out of your action directive definition and the action directives will use whatever scope they are rendered in.

Angular validation directive not working properly

I am using custom angular directive for showing validation. Directive code is as below
angularFormsApp.directive('showErrors',['$timeout', function ($timeout) {
return {
restrict: 'A',
require: '^form',
link: function (scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box so we know the property to check
// on the form controller
var inputName = inputNgEl.attr('name');
var helpText = angular.element(el[0].querySelector(".help-block"));
// only apply the has-error class after the user leaves the text box
inputNgEl.bind('blur', function () {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
helpText.toggleClass('hide', formCtrl[inputName].$valid);
});
scope.$on('show-errors-event', function () {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
scope.$on('hide-errors-event', function () {
$timeout(function () {
el.removeClass('has-error');
}, 0, false);
});
}
}
}]);
and Html is as below
<div class="container" id="login-form">
<img src="assets/img/logo-big.png">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h2>Login Form</h2>
</div>
<div class="panel-body">
<form name="loginForm" class="form-horizontal" novalidate>
<div class="form-group mb-md" show-errors>
<div class="col-xs-12">
<div class="input-group">
<span class="input-group-addon">
<i class="ti ti-user"></i>
</span>
<input type="text" class="form-control" placeholder="Username" autocomplete="Off" ng-required="true" name="username" autofocus ng-model="loginUser.username">
</div>
<span class="help-block" ng-if="loginForm.username.$error.required">Username is required</span>
</div>
</div>
<div class="form-group mb-md" show-errors>
<div class="col-xs-12" >
<div class="input-group">
<span class="input-group-addon">
<i class="ti ti-key"></i>
</span>
<input type="password" class="form-control" placeholder="Password"
name="password"
ng-model="loginUser.password" autocomplete="Off"
ng-required="true">
</div>
<span class="help-block" ng-if="loginForm.password.$error.required">Password is required</span>
</div>
</div>
<div class="form-group mb-n">
<div class="col-xs-12">
Forgot password?
<div class="checkbox-inline icheck pull-right p-n">
<label for="">
<input type="checkbox"></input>
Remember me
</label>
</div>
</div>
</div>
</form>
</div>
<div class="panel-footer">
<div class="clearfix">
Register
Login
</div>
</div>
</div>
</div>
</div>
</div>
Controller code :
var loginController = function ($scope, $window, $routeParams, $uibModal, $location, $filter, $rootScope, DataService, SharedProperties) {
$rootScope.bodylayout = 'focused-form animated-content';
$scope.loginUser = {
username: "",
password:""
}
$scope.load = function () {
//getAppointmentInfo();
};
$scope.SubmitLoginForm = function () {
$scope.$broadcast('show-errors-event');
if ($scope.loginForm.$invalid)
return;
}
}
angularFormsApp.controller("loginController", ["$scope", "$window", "$routeParams", "$uibModal", "$location", "$filter", "$rootScope", "DataService", "SharedProperties", loginController]);
Now When I open form below input control validation span is displaying by default . When I click on Login button then its showing in red and working fine.
problem is it shouldn't show by default when Page is opend.. Please see image below
Instead of this
loginForm.password.$error.required
try this
(loginForm.$submitted || loginForm.username.$dirty) && loginForm.password.$error.required
Take a look at the ng-messages directive. Its fairly elegant. Example:
<form name="myForm">
<input type="text" ng-model="field" name="myField" required minlength="5" />
<div ng-messages="myForm.myField.$error">
<div ng-message="required">You did not enter a field</div>
<div ng-message="minlength">The value entered is too short</div>
</div>
</form>
You can then combine it with any form validation. Just place the error messages from the validators onto the elements $error object and they are automatically rendered in your UI.
I ended up here as part of my search for an issue. In my case I was using a directive with a changing minimum value like this:
ngOnChanges(changes: SimpleChanges) {
if (changes.minDate && this.control) {
this.control.updateValueAndValidity({ onlySelf: true });
}
}
This means that the form will not be updated, I removed onlySelf and it worked correctly.
this.control.updateValueAndValidity();
Just leaving this as a breadcrumb in case someone else does something similar.

input ng-model within ng-repeat

I am repeating a list of tasks that I would like other users to be able to comment on using an input field. I repeat the list with ng-repeat and am trying to send the value of the comment input to the server with ng-model and scope. I am testing by console logging but it shows as undefined. Please help!
Html:
<div class="taskContainer">
<div ng-repeat='task in taskList' class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="newComment" type="text" placeholder="comments">
<button ng-click='comment(task.taskId)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
JS controller:
$scope.comment = function(id,text){
console.log(`send comment text ${$scope.newComment}`);
console.log(`task Id: ${id}`);
};
This is the first time I've tried to do more than display itmes with ng-repeat
You're getting undefined because ngRepeat creates its own $scope.
Always assign ngModel using Dot Rule or controller-as-syntax.
Put it in your controller:
$scope.model = {};
Then use the ngModel as this:
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
Then you can have something like this:
<div class="taskContainer">
<div ng-repeat="task in taskList track by $index" class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
<button ng-click='comment($index)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
$scope.comment = function(index) {
console.log(`send comment text ${$scope.model.newComment[index]}`);
console.log(`task Id: ${taskList[index].id}`);
};
Note: Your function is expecting 2 parameters, you should change it to:
$scope.comment = function(id) {
Thanks for the help from #developer033.
Here is what solved my problem:
HTML:
<div class="taskContainer">
<div ng-repeat="task in taskList track by $index" class="task">
<div class="postedBy">
<h6>{{task.user.userName}}</h6>
</div>
<h4>{{task.taskText}}</h4>
<div class="comments">
<input ng-model="model.newComment[$index]" type="text" placeholder="comments">
<button ng-click='comment(task.taskId,$index)' type="button" name="button">Add</button>
<h6>{{task.commentText}}</h6>
</div>
</div>
</div>
and the JS:
$scope.model = {};
$scope.comment = function(id, index) {
console.log(`send comment text ${$scope.model.newComment[index]}`);
console.log(`task Id: ${id}`);
};
HTML,
<input ng-model="newComment" type="text" placeholder="comments">
<button ng-click='comment(task.taskId, newComment)' type="button" name="button">Add</button>
JavaScript,
$scope.comment = function(id, text) {
console.log(`task Id: ${id}`);
console.log(`send comment text ${text}`);
};

AngularJS refresh smart table after inserting new record in Bootstrap Modal Form

I use angular-bootstrap and and Angular Smart table.
I have a modal form which adds new records to database and shows the list in my smart table. Adding new records is working fine but how do I refresh my smart table after a new record is inserted into the database.
Controller
//ajax request to gather data and list in smart table
october.controllers['dashboard/feeds'] = function ($scope, $filter , $request, $modal, $log, $http) {
$scope.api = $request('onFeeds', {success: function(data, scope){
this.success(data).done(function() {
$scope.rowCollection = [];
$scope.rowCollection = angular.fromJson(data.result);
$scope.displayedCollection = [].concat($scope.rowCollection);
});
}
});
}
//Modal
var ModalInstanceCtrl = function ($scope, $modalInstance, $request, $filter) {
$scope.save = function (data) {
$request('onAddFeed',
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
});
};
};
Template
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">neue Feed eintragen!</h3>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<input type=hidden ng-init="formInfo.user_id = {% endverbatim %} {{ user.id }} ">
{%verbatim %}
<div class="form-group">
<label for="inputName3" class="col-sm-2 control-label">Feed Name</label>
<div class="col-sm-8">
<input class="form-control" id="inputName3" placeholder="Feed Name" ng-model="formInfo.name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Feed Type</label>
<div class="col-sm-8">
<select ng-model="formInfo.feed_type" class="form-control">
<option>Select Feed Source</option>
<option value="api">API</option>
<option value="xml">XML</option>
<option value="csv">CSV</option>
<option value="json">JSON</option>
<option value="upload">Upload</option>
</select>
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='api'">
<label for="selectAPI" class="col-sm-2 control-label">Select API</label>
<div class="col-sm-8">
<select ng-change="selectAction(item.id)" ng-model="formInfo.network_id" ng-options="item.id as item.name for item in networks" class="form-control"> </select>
</div>
</div>
<div class="form-group" ng-repeat="setup in setups">
<label for="setup" class="col-sm-2 control-label">{{setup}}</label>
<div class="col-sm-8">
<input ng-model="formInfo['api_credentials'][setup]" class="form-control" placeholder="Enter your {{setup}}">
</div>
</div>
<div class="form-group" ng-show="formInfo.feed_type =='xml' || formInfo.feed_type =='csv' ">
<label for="inputPassword3" class="col-sm-2 control-label">Source</label>
<div class="col-sm-8">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-link"></i></div>
<input ng-model="formInfo.source" type="text" class="form-control" id="sourceInput" placeholder="URL">
</div>
</div>
</div>
</div>
<span>{{formInfo}}</span>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" ng-click="save(formInfo)">Save</button>
<button type="button" class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
{data:data,
success: function(data){
this.success(data);
$scope.refresh();
$modalInstance.close();
}
In the above code Instead of $scope.refresh() use $route.reload() to
Update the records before closing Modal Instance.
reload() Causes $route service to reload the current route even if $location hasn't changed
To refresh the smart-table you can add or remove items or just recreate the array.
$scope.tableData = [].concat($scope.tableData);
The thing that worked for me (and appears to be causing you the problem) is to set displayedCollection to an empty array. Smart Table will fill it with whatever paged, filtered, or sorted data you designate. Something like this:
<table st-table="displayedCollection" st-safe-src="rowCollection">
All of a sudden, rowCollection.push(data) automatically updated the Smart Table.

Resources