// 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;
Related
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);
})
};
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
I have school task.
We have a HTML code like this:
<html ng-app="myTest">
<head><script type="text/javascript" src="../myScript.js"></script>
</head>
<body id="tst" class="textpage" ng-controller="TestController as testcon">
<form class="" id="frm" ng-submit="doStuff()">
<div class="form-group">
{{testinfo}}
</div>
<div class="form-group">
<button type="submit" id="sbtn" name="sbtn">testSubmit</button>
</div>
</form>
</body>
</html>
Content of javascript with name myScript.js is this:
var tester = angular.module('myTest', ['ui.mask']);
tester.controller('TestController', ['$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) {
$scope.doStuff = function () {
{
$scope.testinfo = 'unknown value';
};
};
}
]);
I have option to add new javascript.
But I am not possible to get value from $scope.testninfo.
I cannot edit existing JavaScript and cannot edit HTML file. I can just add new javascript.
Is there option how to get value from $scope.testinfo in another javascript?
Thanks.
You can use broadcast
From controller 1 we broadcast an event
$scope.$broadcast('myEvent',anyData);
controller 2 will receive our event
$scope.$on('myEvent', function(event,anyData) {
//code for controller 2
});
here anyData represent your object to be passed
Use ng-model.
<div class="form-group">
<input type="text" ng-model="testinfo">
</div>
I dont think it is possible without appending the existing javascript/html. Because the $scope of the TestController cannot be accessed from another controller (file).
If you COULD append the HTML you could use the $rootscope, in that way the value, which is set by the TestController is accessible from another controller. Or you can add a Global app value. I created a fiddle which show the two options: https://jsfiddle.net/Appiez/wnyb9pxc/2/
var tester = angular.module('myTest', []);
tester.value('globalVar', { value: '' });
tester.controller('TestController', ['$rootScope', '$scope', '$http', '$location', '$window', 'globalVar', function ($rootScope, $scope, $http, $location, $window, globalVar) {
$scope.doStuff = function () {
{
$rootScope.testinfo = 'this is the new value';
globalVar.value = 'a global value';
};
};
}
]);
tester.controller('TestController2', ['$rootScope', '$scope', 'globalVar', function ($rootScope, $scope, globalVar) {
$scope.doStuff2 = function () {
{
alert($rootScope.testinfo);
alert(globalVar.value);
};
};
}
]);
This is what services are for in angular. They ferry data across controllers. You can use NG's $broadcast to publish events that contain data, but Providers, Services, and Factories are built to solve this.
angular.module('krs', [])
.controller('OneCtrl', function($scope, data){
$scope.theData = data.getData();
})
.controller('TwoCtrl', function($scope, data){
$scope.theData = data.getData();
})
.service('data', function(){
return {
getData: function(){
return ["Foo", "Bar"];
}
}
});
Here's a fiddle to help get you into the swing of things. Good luck in school!
My setup is NodeJS, MongoDB, and Angular. I'm currently trying to add POSTing capability to my test code but can't quite wrap my head around it. Currently I can pull data from the DB and I threw together a quick and dirty form/factory based on a number of examples I've seen to try to get the POST function working.
The problem I'm running into is actually getting the values to be added to the DB. When I submit the form, a new ObjectID is created in the DB with a "_v" field and a value of 0. So I know the POST is at least being sent to the DB, but the values I want are not. I'm sure I'm doing something stupid and any help is greatly appreciated.
Here is my controller/factory setup: (I named the POST factory "taco" so it would stand out. Also because they're delicious.)
angular.module('app', ['ngRoute'])
.factory('Users', ['$http', function($http) {
return $http.get('/users');
}])
.factory('taco', ['$http', function($http) {
return $http.post('/users');
}])
.controller('UserController', ['$scope', 'Users', function($scope, Users) {
Users.success(function(data) {
$scope.users = data;
}).error(function(data, error) {
console.log(error);
$scope.users = [];
});
}])
.controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
$scope.submit = function() {
if ($scope.users.name) {
$scope.name.post(this.name);
$scope.name = '';
}
};
}]);
Here is my form:
<div>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter the things:<br/>
<input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
<input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
<input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
To post using the $http service you can do:
angular.module('myApp')
.controller('MyController', function($scope, $http) {
$http.post('/destination', {my: 'data'});
});
You're not sending any data in your POST request. The taco service just executes a $http.post call and returns the promise.
Please look at the $http service documents: https://docs.angularjs.org/api/ng/service/$http
I would define a function submit that would send the data once a user clicks on submit:
$scope.submit = function() {
$http.post('/destination', {my: 'data'});
}
I've been playing around with this bug but I can't seem to figure it out. The problem started when I pushed the angular-bootstrap models I had added to the prod server. The original error was this:
"AngularJS Error: Unknown provider: aProvider <- a"
I'm pretty sure I was getting that error because my files weren't minifying correctly. So I went through my controllers and found that I wasn't $injecting $modal instance into my controllers and that's when I ran into this problem.
Whenever I inject $modalInstance into my controller in the minified format I get this error. I am not using the format angular-bootstrap suggests because I have a lot going on and many controllers on the site I'm building so I combined everything into one controller instead of several functions.
My Controller:
.controller('CreateGroupCtrl', ['$scope', '$http', '$window', '$cookies', '$modal', '$log', 'FeedService', '$modalInstance',
function CreateGroupCtrl($scope, $http, $window, $cookies, $modal, $log, $modalInstance, FeedService) {
$scope.createGroupCall = function createGroupCall(teacher, name) {
if(teacher != null && name != null) {
FeedService.createGroupCall($cookies.token, $window.sessionStorage.user, teacher, name).success(function(data) {
console.log('GroupCreated');
}).error (function(status,data,token) {
console.log(status);
console.log(data);
});
} else {
alert("Error!");
}
}
/***********ANGULAR-UI MODAL CODE**********/
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'CreateGroupContent.html',
controller: CreateGroupCtrl,
size: size
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
My Template:
<button ng-controller="CreateGroupCtrl" ng-click="open()" type="button" id="creategroup" class="btn ns-btn">
<img class="ns-add" src="images/createGroup.png">
<p class="create">Create Group</p>
</button>
<div>
<script type="text/ng-template" id="CreateGroupContent.html">
<div class="modal-header">
<h2 class="modal-title ns-modal-title">Create A Group</h2>
<button class="ns-modal-close" ng-click="cancel()"><img src="images/xCancel.png"></button>
</div>
<div class="modal-body">
<form class="form-signin" role="form">
<input type="text" class="form-control ns-modal-form" placeholder="Teacher" ng-model="create.teacher" required autofocus>
<input type="text" class="form-control ns-modal-form" placeholder="Group Name" ng-model="create.name" required>
</form>
</div>
<div class="modal-footer">
<button class="btn ns-modal-add ns-btn" ng-click="createGroupCall(create.teacher, create.name); ok();" type="submit">Create</button>
</div>
</div>
</script>
</div>
At first, you need to inject all in its order.
Also, you should inject $modal into the controller in which you would like to create your modal view. And the $modalInstance can be injected ONLY into the controller which is used for this $modal window. In your case you use the same controller, so you couldn't inject $modalInstance
Demo: http://plnkr.co/edit/khzNQ0?p=preview
Also, in your case (when you use only 1 controller) - you can pass as object field scope which will be used as parent of $scope for your modal view. By default it is $rootScope, but you can type:
$scope.open = function (size) {
var modalInstance = $modal.open({
templateUrl: 'CreateGroupContent.html',
controller: CreateGroupCtrl,
size: size,
scope: $scope
});
So now your functions ok() and cancel() will be available in your modal view and modal scope.
Looks like your FeedService and $modalInstance are mixed up. They need to be in the same order.