I have a piece of angular code like below:
$scope.someFunction = function(){
$scope.val = $scope.value2.length;
}
I would like to test the above piece of code, for which i am doing something like below:
describe('test that', function() {
beforeEach(module('waldo'));
describe('MainController', function () {
var $scope, createController;
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
createController = function (value2) {
return $controller('MainController', {
$scope: $scope,
value2: value2
});
};
}));
it('exists', function () {
var value2 = ["google", "yahoo"];
var controller = createController(value2);
expect(controller).not.toBeNull();
$scope.val = 10;
$scope.someFunction();
assert.equal($scope.val, value2.length);
});
});
});
I am getting an error like below:
TypeError: Cannot read property 'length' of undefined
at Scope.MainController.$scope.someFunction (absolute/home/guru/app/controllers/MainController.js?131fd944e9e94b3a4ee4eb524e48e17a87dd4820:43:51)
createController = function (value2) {
$scope.value2 = value2;
return $controller('MainController', {
$scope: $scope
});
};
Every Angular controller has an associated $scope object.
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
</body>
Reference:
https://docs.angularjs.org/guide/forms
Related
I tried to extend the "Heros" application from the AngularJS documentation
I wanted to add the functionality of creating/adding a hero.
In the HeroList.js from this plunk I am able to add a new hero after clicking the button Add from the HeroList.html.
However, if I'm updating the input fields (let's say name) they get edited in the list as well.
For example, if I added a new hero (Captain America), click Add, and then type Robby, Captain America will be concatenated with Robbie.
(function(angular) {
'use strict';
function HeroListController($scope, $element, $attrs) {
var ctrl = this;
// This would be loaded by $http etc.
ctrl.list = [
{
name: 'Superman',
location: ''
},
{
name: 'Batman',
location: 'Wayne Manor'
}
];
ctrl.create = function(hero) {
ctrl.list.push(hero);
};
ctrl.updateHero = function(hero, prop, value) {
hero[prop] = value;
};
ctrl.deleteHero = function(hero) {
var idx = ctrl.list.indexOf(hero);
if (idx >= 0) {
ctrl.list.splice(idx, 1);
}
};
}
angular.module('heroApp').component('heroList', {
templateUrl: 'heroList.html',
controller: HeroListController,
bindings: {
onCreate: '&'
}
});
})(window.angular);
Your Problem is that you are having reference to same Hero Object so when you update the text fields it will automatically update it in the list. To Avoid this problem you can use angular.Copy()
ctrl.create = function(hero) {
ctrl.list.push(angular.copy(hero));
};
this will create separate copy to be added to the list.
here is some code you can refer https://plnkr.co/edit/?p=preview
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-forms-simple-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="formExample">
<div ng-controller="ExampleController">
<form novalidate class="simple-form">
<label>Name: <input type="text" ng-model="user.name" /></label><br />
<label>E-mail: <input type="email" ng-model="user.email" /></label><br />
Best Editor: <label><input type="radio" ng-model="user.preference" value="vi" />vi</label>
<label><input type="radio" ng-model="user.preference" value="emacs" />emacs</label><br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
<pre>user = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.master = {};
$scope.update = function(user) {
$scope.master = angular.copy(user);
};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
</script>
</body>
</html>
<!--
Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
I'm using ionic to build a webapp, and I want to use ng-model bind input form value.
It is weird that I am not getting model.cellphone's value, but I got model.password's value.
Currently I cannot figure this out. Can anybody help me?
html:
<ion-view>
<ion-content class="login-content">
<div class="login-form">
<input type="text" class="login-form-cellphone" ng-model="model.cellphone" placeholder="please input your phonenumber" required minlength="11" maxlength="11"/>
<input type="password" class="login-form-password" ng-model="model.password" placeholder="please input your password" required/>
<button class="login-form-btn" ng-click="login()">Login</button>
</div>
</ion-content>
</ion-view>
js:
.controller('LoginCtrl', ['$scope', '$state', '$stateParams', 'RouteService', 'ApiService', function ($scope, $state, $stateParams, RouteService, ApiService) {
var route = 'app.home.login';
var params = $stateParams;
$scope.model = {};
$scope.doRefresh = function () {
$scope.isChecked = true;
};
$scope.goBack = function () {
$state.go(params.previewRoute);
};
$scope.clickCheck = function () {
$scope.isChecked = !$scope.isChecked;
};
$scope.login = function () {
console.log($scope.model.cellphone, $scope.model.password, $scope.isChecked);
if (!$scope.model.cellphone) {
console.log('cellphone');
return;
}
if (!$scope.model.password) {
console.log('password');
return;
}
if (!$scope.isChecked) {
console.log('isChecked');
return;
}
ApiService.login(
$scope.model.cellphone,
$scope.model.password,
null,
function (status) {
if (status === 1)
$state.go(params.previewRoute);
})
};
// SERVICES
app.factory('searchFactory', ['$http', function($http) {
return $http.post("/api", { tag: "food" });
}]);
// CONTROLLERS
app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
$scope.submit = function () {
searchFactory.then(function(response) {
$scope.recipeData = JSON.parse(response.data);
});
};
// HTML
<form ng-submit="submit()">
<div class="form-group">
<input type="text" ng-model="recipeTag" class="form-control" />
<input type="submit" class="btn btn-primary" value="Find Recipes" />
</div>
</form>
Does anyone know how I can use $scope.recipeTag from ng-model to replace "food" in the factory? I need to be able to pass the form input as a parameter into the factory.
you need to create a funtion that expects a parameter in your factory.
Example:
var factory= {
post: function(customTag) {
return $http.post("/api", { tag: customTag });
}
};
return factory;
How can I add a new object which be read from input form in AngularJS ?
my JSON :
{
"1": {
"name": "Audi",
"year": "1993",
},
"2": {
"name": "BMW",
"year": "2012",
}
}
my Add.html:
<form name="addForm" ng-controller="AddCtrl" ng-submit="AddCtrl.newcar.(car)">
<p>name: <input type="text" ng-model="AddCtrl.newcar.name"></p>
<p>year: <input type="text" ng-model="AddCtrl.newcar.year"></p>
<input type="submit" value="send" />
</form>
my AddCtrl :
angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
$routeParams) {
$http.get('scripts/controllers/cars.json').success (function(data){
});
this.newcar = {};
this.addCar = function(car) {
car.name.push(this.name);
this.newcar ={};
};
}]
);
I want to have page that after filling all inputs and cliking submit button new car will be added in JSON with next id. Where and what should I add to have achieve this ?
Your code is wrong.
angular.module('motoApp')
.controller('AddCtrl', ['$scope','$http', '$routeParams', function($scope, $http,
$routeParams) {
$scope.cars = [];
$http.get('scripts/controllers/cars.json').success (function(data){
$scope.cars = data;
});
$scope.addCar = function() {
$scope.cars.push($scope.car.name);
};
}]
);
form
<form name="addForm" ng-controller="AddCtrl" ng-submit="addCar()">
<p>name: <input type="text" ng-model="car.name"></p>
<p>year: <input type="text" ng-model="car.year"></p>
<input type="submit" value="send" />
</form>
Working fiddle:http://jsfiddle.net/wyorodt0/
Search form xmlhttprequest works fine.
is there any option to use this function while typing instead of submit form ?
function customersController($scope, $http) {
$scope.search = function() {
$scope.url = 'http://www.vanmaram.com/json_result.php?en=' + $scope.keywords;
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in <li> element
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords">
<input type="submit" value="Search">
</form>
<ul>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
</div>
Hi Please check this example in plunkr [link:http://plnkr.co/edit/6kuVR4?p=preview]
Hope it helps.
Js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected = "";
$scope.countries = ["India", "Australia", "Japan"];
});
app.directive('autoComplete', function($timeout) {
return function(scope, iElement, iAttrs) {
iElement.autocomplete({
source: scope[iAttrs.uiItems],
select: function() {
$timeout(function() {
iElement.trigger('input');
}, 0);
}
});
};
});
In HTML
<body ng-controller="MainCtrl">
<p>Countries {{countries|json}}!</p>
<div ng-app="MyModule">
<div>
<input auto-complete="" ui-items="countries" ng-model="selected" />selected = {{selected}}
</div>
</div>
</body>
used library jqueryui/1.8.16/jquery-ui.js
The solution found with ng-change which call the same function of form submit
function customersController($scope, $http) {
$scope.suggestword = function(argument) {
$scope.url = 'http://www.vanmaram.com/ajax_json_suggestion.php?en=' + $scope.keywords; // The url of our search
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.suggetionresult = data; // Show result from server in <li> element
$scope.result = null;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords" ng-change="suggestword()">
<input type="submit" value="Search">
</form>
<ul ng-if='result.length'>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
<div id="suggestion" ng-if='suggetionresult.length > 1'>
Suggestions: <a ng-repeat="word in suggetionresult | limitTo:9">{{ word }}</a>
</div>
</div>