I would like to submit a search form on page load if search terms were specified in the route. The problem is that searchForm isn't defined yet when search() runs. I've seen others get this to work by putting ng-controller right on the form element, but I have multiple forms on this page, so the controller has to be a parent of the forms.
How can I ensure the form is defined when I call search()?
myModule.controller('MyController', ['$scope', '$routeParams',
function($scope, $routeParams){
$scope.model = {searchTerms: ""};
$scope.search = function(){
if($scope.searchForm.$valid){
...
}
};
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
}]);
View:
<div ng-controller="MyController">
<form name="searchForm" ng-submit="search()">
...
</form>
<form name="detailForm" ng-submit="save()">
...
</form>
</div>
This seems to work:
$scope.$on('$routeChangeSuccess', function () {
if($routeParams.terms !=""){
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
}
});
Have you tried just using $watch on searchForm?
if($routeParams.terms != "") {
var unregister = $scope.$watch(function() {
return $scope.searchForm;
}, function() {
// might want to wrap this an if-statement so you can wait until the proper change.
unregister(); //stop watching
$scope.model.searchTerms = $routeParams.terms;
$scope.search();
});
}
Related
small question (possible a logic err), I am trying to get the checkbox to update itself automatically after clicking it and in the same time using the rest api to PUT the changes in DB, and the PUT mothod works, it updates the DB but it`s not updating the checkbox state itself only if I refresh the page, the checkbox will update.
And I have this simple code:
<input type="checkbox" ng-checked="action.state" ng-click="setState($event, key, action)"><div class="track"><div class="handle"></div></div>
and back-end as this:
.controller('Actions', function ($scope, $filter, $resource, $ionicActionSheet, $ionicModal) {
var actionListResource = $resource('/api/actions/');
actionListResource.query(function (data) {
$scope.actions = data;
});
$scope.setState = function (event, index, action) {
if (action.widget === 'toggle' && action.state === 1) {
action.state = 0;
}
else {
action.state = 1;
}
event.preventDefault();
var actionsResource = $resource('/api/actions/:actionId/', {actionId:'#id'}, {
'update': {
method: 'PUT'
}
});
};
...more code here
})
action.state is always a 1 or 0 value, I've checked the $scope.actions[index].state and it`s updating itself when I click the checkbox.
Thank you!
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="myCtrl">
<input type="checkbox" ng-model="action" ng-click="setState()">
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
$scope.setState = function() {
window.alert($scope.action);
// $scope.action value will be true or false
};
}]);
</script>
</body>
</html>
Try ng-model instead of ng-checked. The toggle stuff looks unecessary. ng-change could also be used to trigger the request.
In their docs they solve exactly the problem you describe.
https://docs.angularjs.org/api/ng/directive/ngChange
I am looking for an callback function after $filter filter completes the filtering the data
HTML
<input type="text" ng-model="searchvalue">
<span ng-click="searchbtn()">Search</span>
JS
$scope.searchbtn = function() {
$scope.loading = true;
$scope.mysearchvalue = $scope.searchvalue;
}
When user enters keyword my data will be filtered and i need a callback function after filtering the data.
i have tried using "DOMSubtreeModified" but returning continues logs
var myElement = angular.element(document.getElementById("mycontent"));
myElement.bind("DOMSubtreeModified", function() {
console.log("keep outputting this message");
});
As said in my comment, why not just use a little delay (debounce) and filter results in controller w/o separate input button. Consider
HTML template
<body ng-controller="MainCtrl">
<pre ng-bind="filteredData | json"></pre>
<input type="text" ng-model="search" ng-model-options="{debounce:250}">
</body>
JavaScript
angular.module('app', [])
.controller('MainCtrl', function($scope, $filter) {
$scope.data = [{text:'aa'},{text:'ab'}];
$scope.$watch('search', function(val) {
$scope.filteredData = $filter('filter')($scope.data, val);
});
});
I'm trying to take the first example from the angular.js homepage and adding in cookie support.
This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/
It is:
<div ng-app="myApp">
<div ng-controller="MyController as mc">
<label>Name:</label>
<input type="text" ng-model="mc.user" placeholder="Enter a name here">
<hr>
<h1>Hello {{mc.user}}!</h1>
</div>
</div>
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', [function($cookies) {
this.getCookieValue = function () {
$cookies.put('user', this.user);
return $cookies.get('user');
}
this.user = this.getCookieValue();
}]);
But it's not working, ive been trying to learn angular.
Thanks
I'd suggest you create a service as such in the app module:
app.service('shareDataService', ['$cookieStore', function ($cookieStore) {
var _setAppData = function (key, data) { //userId, userName) {
$cookieStore.put(key, data);
};
var _getAppData = function (key) {
var appData = $cookieStore.get(key);
return appData;
};
return {
setAppData: _setAppData,
getAppData: _getAppData
};
}]);
Inject the shareDataService in the controller to set and get cookie value
as:
//set
var userData = { 'userId': $scope.userId, 'userName': $scope.userName };
shareDataService.setAppData('userData', userData);
//get
var sharedUserData = shareDataService.getAppData('userData');
$scope.userId = sharedUserData.userId;
$scope.userName = sharedUserData.userName;
Working Fiddle: https://jsfiddle.net/y7dxa6n8/10/
I have used the cookie service between two controllers. Fill out the text box to see how it gets utilized.
ok, examined your code once again, and here is your answer
https://jsfiddle.net/wz3kgak3/
problem - wrong syntax: notice definition of controller, not using [] as second parameter
If you are using [] in controller, you must use it this way:
myApp.controller('MyController', ['$cookies', function($cookies) {
....
}]);
this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies
problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;
problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:
$watch('user', function(newValue) {
$cookies.user = newValues;
});
or do it via some event (click, submit or i dont know where)
EDIT: full working example with $scope
https://jsfiddle.net/mwcxv820/
I have html page like
<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>
And i have angular Js code is
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
{
$http.get('data/userData.json').success (function(data){
$scope.users = data;
$scope.users.doClick = function(user,event) {
userInfo(user);
}
});
}]);
function userInfo(users)
{
console.log(user);
userDirectory.controller("userDetailsControl", function($scope)
{
console.log('well')
$scope.user = users;
console.log($scope.user)
});
}
Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).
I am new one in angular jS. I dont know this logic is correct or not.
I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section
First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.
Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
$scope.selectUser = function(user){
$rootScope.selectedUser = user;
}
$http.get('data/userData.json')
.success (function(data){
$scope.users = data;
});
})
.controller("userDetailsControl", function($scope, $rootScope){
$rootScope.$watch("selectedUser", function(newVal){
$scope.user = newVal;
}
}
and in your HTML:
<div ng-controller="userListControl">
<button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
<div>{{user.name}}</div>
<div>{{user.otherDetails}}</div>
</div>
I have a form and I want to catch it submission, check validation of data and than submit form to the action inside the HTML form.
<div ng-controller="contactCtrl">
<form action="someAction" method="post" name="contactForm" class="clearfix frmContact">
<div class="one_half">
<input id="txtName" ng-model="name" value="" class="form-control">
</div>
<button ng_click="save($event)" type="submit">Send Message</button>
</form>
</div>
and my js:
var app = angular.module('bloompyApp', []);
app.controller("contactCtrl", function($scope, $http) {
$scope.email = "";
$scope.name = "";
$scope.message = "";
$scope.left = function() {return 100 - $scope.message.length;};
$scope.clear = function() {$scope.message = "";};
$scope.save = function(ev) {
ev.preventDefault();
console.log(angular.element(document.querySelector('body')));
if ($scope.contactForm.$valid) {
$http.get("/posts/")
.success(function(response) {console.log(response);});
}
};
});
You should:
Use the ng-submit directive on your form
Pass the form element to your save() method
Use the $http service to post
var ctrl = function ($scope, $http, $log) {
$scope.save = function (form) {
//if (!$scope.contactForm.$valid) return;
var url = form.attributes["target"];
$log.debug(url);
$http
.post(url, { email: $scope.email, name: $scope.name })
.success(function (response) {
$log.debug(response);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<form ng-submit="save($element.action)">
<button type="submit">Send Message</button>
</form>
</div>
I really advice you to follow this page of the docs from the beginning to the end, you'll change your approach to form using AngularJS :)
https://docs.angularjs.org/guide/forms
Use ng-submit instead on the form element
"Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes."
It will also only run the expressions if the native html5 validation is valid