I am trying to call text from input using angular js - javascript

I am trying to call text that has been added to an input using Angular JS, however in my console log I keep getting undefined.
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="serverip"/>
<button ng-click="save(serverip)">Save</button>
</div>
</div>
</li>
</ul>
</div>
js code
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.save = function(){
console.log($scope.serverip)
}
})

You don't need to pass the parameter to the save function (and your definition of save doesn't include it).
Change the button to:
<button ng-click="save()">Save</button>
Or either accept the parameter in the function declaration:
$scope.save = function(serverip){
console.log(serverip)
}

ng-repeat creates a new scope, inheriting from the scope above it. You are assigning serverip to this newly created scope. Thus, $scope in the favouritesController's context has no record of this. You should accept a parameter in your save function and log that (as you are passing this function the argument, anyways.)
Edit:
or, as an alternative... Expose a property that will be inherited by ng-repeat:
Controller:
myApp.controller('favouritesController', function($scope, $http, $rootScope, $route, $location) {
$scope.ip = { serverip:'' };
$scope.save = function(){
console.log($scope.ip.serverip)
}
});
Template
<div ng-controller="favouritesController" class="col-xs-12 favList">
<input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-12 FavInput" placeholder="Add A Favourite">
<ul>
<li ng-repeat="weatherList in weatherLists" class="col-xs-12">
<span class="col-xs-12 col-sm-8">{{weatherList._id + ' / ' + weatherList.place}}</span>
<div class="col-xs-12 col-sm-2">
<button type="button" name="button" class="deleFav" ng-click="delete(weatherList)">Delete</button>
<div class="col-xs-12">
<input type="text" ng-model="ip.serverip"/>
<button ng-click="save()">Save</button>
</div>
</div>
</li>
</ul>
</div>

Related

ANGULARJS: directive inside another directive doesn't have access to ng-model from HTML

I recently had a coding challenge that I got rejected for because it was garbage. Didn't have a lot of time so I threw everything together in one giant HTML file/angular controller, so I'm in the middle of rewriting it in templates to try to make it more reusable. So far it's going well, but I'm having some trouble with an html template not being able to access ng-model. Whenever I console.log the ng-model, I get undefined.
Here's the top layer HTML:
<div class="col-md-8 box">
<div class="panel panel-default">
<div class="panel-heading">Companies</div>
<div class="panel-body">
<div ng-repeat="company in companies">
<div class="panel panel-default">
<div class="panel-heading">Name: {{company.name}} <button ng-click="companies[$index].editCompany = !companies[$index].editCompany" class="pull-right">EDIT COMPANY</button></div>
<div class="panel-body" ng-if="!companies[$index].editCompany">
<p>Address: {{company.address}}</p>
<p>Revenue: {{company.revenue}}</p>
<p>Phone Number: {{company.phone}}</p>
<button ng-click="getPeople(companies[$index]._id, $index); companies[$index].viewEmployees = !companies[$index].viewEmployees">People Who Work Here</button>
<div ng-if="companies[$index].viewEmployees">
<show-employees-list></show-employees-list>
</div>
</div>
</div>
<div ng-if="companies[$index].editCompany">
<edit-company-directive></edit-company-directive>
</div>
</div>
</div>
</div>
</div>
And here's the HTML for the directive:
<div class="employee-box" ng-repeat="employee in companies[$index].employees">
<span class="glyphicon glyphicon-edit pull-right" ng-click="companies[$index].editEmployee = !companies[$index].editEmployee; clickEdit()"></span>
<span class="glyphicon glyphicon-remove pull-right" ng-click="deletePerson(employee._id, $index, companies[$parent.$index].employees)"></span>
<div ng-if="!companies[$index].editEmployee">
<div>
<p><b>Name:</b> {{employee.name}}</p>
<p><b>Email:</b> {{employee.email}}</p>
</div>
</div>
<div ng-if="companies[$index].editEmployee" class="form-body">
<form name="editPersonForm" ng-submit="editPerson(employee._id, $parent.$parent.index, $parent.index)">
<input type="text" ng-model="nameEdit" id="nameEdit" placeholder="Employee" class="form-control" required></input>
<input type="text" ng-model="emailEdit" id="emailEdit" placeholder="Email" class="form-control" required></input>
<button type="submit" id="submitButton" class="btn btn-success form-actions">Submit</button>
</form>
</div>
</div>
And here's the directive code:
'use strict';
(function() {
angular
.module('sigFig')
.directive('showEmployeesList', showEmployeesList);
function showEmployeesList(sigFigFactory) {
var directive = {
restrict: 'E',
templateUrl: 'Directives/showEmployeesList/showEmployeesList.html',
scope: '=',
require: '^parentDirective',
link: link
};
return directive;
function link(scope, element, attra, controller) {
scope.deletePerson = function(id, index, employees) {
sigFigFactory.deletePerson(id).then(function(response) {
employees.splice(index, 1);
return response;
})
};
scope.editPerson = function(personId, index1, index2) {
scope.person = {
name: scope.nameEdit,
email: scope.emailEdit
};
console.log('person ', scope.person);
};
}
}
})();
I'm thinking it's some sort of scoping issue that I just don't see, and hoping someone can help. When I console.log that person object I get undefined for both properties.
it's good idea to use angular directive, and also you need to read more about it:
you just define scope as variable but it's object, and there isn't scope.nameEdit to console
app.directive("name", function() {
return {
templateUrl: "your.html", //it's string
restrict: 'E',
scope: { //it's object
param1: "=" //var
param2: "#" //string
param3: "&" //method and etc
},
link: function(scope){ //it's function
//scope.param1
//scope.param2
//scope.param3
}
}
})
<name param1="{foo: 'test'}" param2="hello" param3="callback"></name>
with directive you can pass everything from your basic view (controller) to the directive, you can $watch value on change in your controller and more options.

AngularJS update the view when $rootScope changes

I'm trying to build an angular application that has a sidebar that updates various elements within the DOM.
Currently I have the following configuration:
index.html
<div id="sidebar" ng-controller='SidebarController' ng-class="myclass" class="col-md-2 animated fadeIn" ui-view="sidebar" ng-cloak>
<i ng-click='toggleSidebar()' class='fa fa-chevron-right'></i>
<div class='col-md-12 main'>
<section id='templates'>
<div class="btn-group">
<label class="active btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t1'">Template 1</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t2'">Template 2</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t3'">Template 3</label>
<label class="btn btn-primary" ng-model="templateModel" ng-click='changeTemplate(templateModel)' uib-btn-radio="'t4'">Template 4</label>
</div>
</section>
</div>
<div class='col-md-12 other'>
<uib-accordion close-others="oneAtATime">
<uib-accordion-group is-open="status.open" heading="Other fun things you can edit" panel-class="">
<section id='Option'>
<span>Select Option type</span>
<div class="btn-group">
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="btn btn-primary" uib-btn-radio="'optiona'">Option A</label>
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="active btn btn-primary" uib-btn-radio="'optionb'">Option B</label>
<label ng-model="optionChoice" ng-click='optionType(optionChoice)' class="btn btn-primary" uib-btn-radio="'optionc'">Option C</label>
</div>
</section>
</uib-accordion-group>
</uib-accordion>
</div>
</div>
<!-- MAIN CONTENT -->
<div id="main-container" class="col-md-10 animated fadeIn" ui-view="mainContent" ng-cloak></div>
and the controller associated with it SidebarController.js:
application.controller('SidebarController', ['$scope', '$rootScope', '$http', '$state', function ($scope, $rootScope, $http, $state, $translate) {
//Select Option
$rootScope.optiona= false;
$rootScope.optionb= true;
$rootScope.optionc= false;
$scope.optionType= function (optionChoice) {
switch (optionChoice) {
case "optiona":
$rootScope.optiona= true;
$rootScope.optionb= false;
$rootScope.optionc= false;
break;
case "optionb":
$rootScope.optionb= true;
$rootScope.optiona= false;
$rootScope.optionc= false;
break;
case "optionc":
$rootScope.optionc= true;
$rootScope.optionb= false;
$rootScope.optiona= false;
break;
}
}
}]);
Then I have another template called home.html:
<div id='mybtn' ng-if="general.optiona" class='alt-btn btn btn-primary' role="button">Option A</div>
<div id='mybtn' ng-if="general.optionb" class='alt-btn btn btn-primary' role="button">Option B</div>
and the controller MainPageController.js:
application.controller('MainPageController', ['$scope', '$rootScope', '$http', '$state', '$window', function ($scope, $rootScope, $http, $state, $window, $translate, $location) {
$scope.general = {
optiona: $rootScope.optiona,
optionb: $rootScope.optionb,
optionc: $rootScope.optionc
}
}]);
My hope would be that the relevant div would show depending on the option selected but that is not the case. Is there a way the MainPageController.js will automatically update when the SidebarController.js updates $rootScope?
Also I know its not best practice to store things in the $rootScope but for this instance I've opted to do it.
I'm also recieving no errors in the console window. The application is running within my browser fine but I'm unable to update the interface accordingly
any help much appreciated!
Do not use $rootScope, this is not what it is meant for.
please read about angular Services and use them instead to share data across different parts of youre application.
any way for youre question - if you want to detect a change in the $rootScope use the $watch function, you should read the documentations anout that also.
Good luck.

ng-change and ng-click not triggering events in controller

I'm trying to create a radio type button selection in AngularJS. Here is my code.
HTML code:
<!-- Page Content -->
<div id="page-wrapper">
<div class="container-fluid">
<h3 class="page-header">Create Products</h3>
<div class="media-list" data-toggle="buttons">
<label class="btn btn-default col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="win" name="platform-selection" id="win-tile" >
<i class="center-block fa fa-windows fa-5x"></i>
<span class="text-center">Windows</span>
</label>
<label class="btn btn-default col-md-offset-custom col-md-2 custom-thumbnail">
<input type="radio" ng-model="platformSel" ng-change="tileSelect(value)" value="mac" name="platform-selection" id="mac-tile">
<i class="center-block fa fa-apple fa-5x"></i>
<span class="text-center">MAC</span>
</label>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
Controller code:
(function() {
'use strict';
function config($routeProvider) {
$routeProvider
.when('/createProduct', {
templateUrl: 'app/components/createProduct/createProductView.html',
controller: 'createProductCtrlr'
});
}
function createProductCtrlr($scope, $rootScope, $location) {
$scope.platformSel = '';
$scope.tileSelect = function(target) {
console.log(target + " selected");
};
}
angular
.module('pacman')
.controller('createProductCtrlr', ['$scope', '$rootScope', '$location', createProductCtrlr])
.config(['$routeProvider', config]);
})();
I don't see any call happening in 'tileSelect' function. I have no clue why.
Any help is appreciated. I'm new to Angular JS.
Is there any error in JavaScript console? As mentioned before you are missing ng-app and ng-controller directives.
<div id="page-wrapper" ng-app="pacman" ng-controller="createProductCtrlr">
The rest of the code almost correct but since you bind the radio to a model variable there is no need for passing argument in ng-change function.
$scope.tileSelect = function() {
console.log($scope.platformSel + " selected");
};
Check this fiddle
Debugging and fixing stuff is real hard. Not as simple as writing code from scratch.
The reason being is, 'data-toggle=buttons' just toggles the bootstrap UI and doesnt make any function calls. Remove the line from html line where class="media-list" and it works.
Answer:
data-toggle="buttons" just toggles the twin button group. Doesnt allow to make function calls.

Controller Function is not getting called on ng-click

This is my View Code
<div ng-controller="signupCtrl">
<ul class="list-group" >
<li class="list-group-item">
<div class="form-group">
<input type="text" ng-model="signupCtrl.firstName">
</div>
...
</div>
<div class="form-group">
<div class="pull-right">
<button ng-click="signupCtrl.signupUser()">Register</button>
</div>
</div>
</li>
</ul>
</div>
Update- This is my Controller Code ##
someAppControllers.controller('signupCtrl', [
'$window',
'$scope',
'HttpReqHandlerService',
'$location',
'localStorageService'],
function($window, $scope, HttpReqHandlerService,
$location, localStorageService) {
$scope.signupUser=function signupUser() {
alert("hello");
}]);
The button is not calling signupUser function in my controller
Use $scope.signupUser instead of this.signupUser
Change you code as
someAppControllers.controller('signupCtrl', ['$window', '$scope',
function ($window, $scope) { // Here you have to define function an pass window and scope
$scope.signupUser = function signupUser() {
alert("hello");
};
}
]);
Additionally, You have syntax error.
HTML
Instead of
<input type="text" ng-model="signupCtrl.firstName">
<button ng-click="signupCtrl.signupUser()">Register</button>
Use
<input type="text" ng-model="firstName">
<button ng-click="signupUser()">Register</button>
You've written your markup as though you used the controller as syntax. To make it work just change your ng-controller="signupCtrl" to ng-controller="signupCtrl as signupCtrl";

Directive template with Input + ng-model = magic?

I'm quite frustrated and apologize in advance for poorly formulated question.
I've created derictive for simple list editing:
angular.module('myApp').
directive('variableList', function () {
return {
restrict: 'AE',
templateUrl: 'variableList.html',
replace: true,
scope: {
value: '='
},
controller: [
'$scope', '$element', '$attrs', '$transclude',
function($scope) {
$scope.removeListItem = function (index) {
$scope.value.splice(index, 1);
};
$scope.addListItem = function () {
$scope.value.push($scope.nextListItem);
$scope.nextListItem = null;
};
}
]
};
});
and template
<div class="variable-list">
<div class="variable-list-items">
<div class="row collapse variable-list-item" ng-repeat="(index, val) in value">
<div class="small-11 columns variable-list-item-value">
<input type="text" ng-model="val" />
</div>
<div class="small-1 columns">
<button class="button alert prefix no-margin icon-minus"
ng-click="removeListItem(index)"></button>
</div>
</div>
</div>
<div class="row collapse variable-list-controls">
<div class="small-11 columns">
<input type="text" ng-model="nextListItem" />
</div>
<div class="small-1 columns">
<button ng-class="{disabled: !nextListItem}"
ng-click="addListItem()"
class="button success prefix no-margin icon-plus"></button>
</div>
</div>
</div>
the important part of template if
<input type="text" ng-model="val" />
In the end I have quite working ui
But inputs for existings items doesnt work! Nothing happen when I try to edit them. Input for new item, add and remove buttons works as intended.
Any ideas?
Edit
I've tried to bind model like this
<input type="text" ng-model="value[key]" />
I was able to edit input but it caused even more magic, after first keypress input loses focus.
Found answer here https://github.com/angular/angular.js/issues/1267
Basically you have to have a . in ng-model or the revers data binding does not work on primitives.

Categories

Resources