Reload or reinitialize angular form after posting data - javascript

I have an angular form to add data in database.I am using angular-fullstack by yeoman.
Now, once data is posted, I can clear ty the form values by assigning an empty object to form scope.
However, I can not add more values without reloading the page.
Also, I have tried this:
var original = $scope.permission;
$scope.reset(original);
$scope.reset= function(original){
$scope.permission= angular.copy(original)
$scope.form2.$setPristine();
$scope.form2.$setUntouched();
}
But has not helped.
Note: $route.reload() is not suitable for me in this case therefore I am trying to find alternatives to do this.

That error seems to be relevant. If I understand correctly you are trying to inject ngRoute module as dependency into your createProjectApp. In that case you should do something like this:
angular.module('createProjectApp', ['ngRoute']);
and make sure you have proper script tag in the header:
<script src="angular-route.js">
Hope this helps.

I'm not sure what your requirements are. But as for $route.reload, I think you're injecting the module incorrectly. There are two things you need to do to get $route.reload() to work. After you've added angular-route.js as a script tag:
1) Change
angular.module('createProjectApp', ['$route'])
to
angular.module('createProjectApp', ['ngRoute'])
According to the documentation, the correct module name is ngRoute
https://docs.angularjs.org/api/ngRoute/service/$route
2) In your controller, you need to include $route as a parameter. Then you can use $reload.route() in that particular controller like so:
createProjectApp.controller('MainController', function ($scope, $route) {
$scope.reload = function(){
$reload.route();
}
}

Related

AngularJs testing. Where to put template

I am currently testing an angularjs directive. This directive has a templateUrl. I would lke to test the view to make sure it was initialized correctly i.e. correct number of buttons, certain elements hidden.
The problem I am having is that when I insert my html file into the template cache I still get :
"message": "Unexpected request: GET partials/stuff/stuff-leader.html
I assumed that when I used the templateCache I would no longer have to use:
$httpBackend.whenGET("partials/stuff/stuff-leader.html").respond([{
userId: 000
}]);
but this does not seem to be the case. I am wondering am I correctly inserting the template, here is how I am doing it:
template = $templateCache.get('/full/root/disk/path/to/file/stuff/stuff-leader.html');
$templateCache.put('/myApp/templates/stuff-leader.html',template);
Is this correct, or should I be placing it somewhere else?
Your normal template is looked for at /partials/stuff/stuff-leader.html, so this is what you need to inject into the template cache instead of /myApp/templates/stuff-leader.html.
You are performing a request with the $templateCache.get. Instead do:
beforeEach(inject(function ($templateCache) { $templateCache.put('partials/stuff/stuff-leader.html', '< div >...TemplateCode....< /div >'); }));

angular how to use scope from a different controller

I have a user.list.ctrl and a user.detail.cntr. All the controllers are build as a module and are injected in a "user-module" which I inject in the app.js. (see the complete code in the plunker below)
my controller module
angular.module('user-module', ['user-module.controllers']);
my user-module
angular.module('demo.app', ['user-module']);
In both controllers i inject user-Fctr with data from a REST factory. (works well)
user.list.cntrl has a $scope.refresh()
user.detail.cntrl has a $scope.update()
user.list.cntrl
When I enter a new record, i call the $scope.refresh() so I can refresh the list. (this is working fine)
user.detail.cntrl
When i click a user from the list, the user detail loads in a different view (works ok)
when I update the user.detail, I want to call $scope.refresh() to update the user.list , but it is not working. I cannot call $scope.refresh()
I thought that since I inject the same factory into both controllers I can use each others $scopes.
Any ideas on how I can use $scope.refresh() (or update the list when I update the user.detail.js)
I make a plunker with all the js files (the plunker is not functional, it is only to show the code that I have)
http://plnkr.co/edit/HtnZiMag0VYCo27F5xqb?p=preview
thanx for taking a look at this
This is a very conceptual problem.
You have created a controller for each "piece" of view because they are meant for different activities. This is the purpose of controllers. So that is right.
However, you are trying to access the refresh function, written in one controller, in another one. Taken literally, this is wrong, since then, refresh is out of place either inside the user list controller or the detail controller.
A function that is meant to control (literally) what is happening on a specific piece of view is a controller. - There you are right having a controller for the list and one for the details.
A function that is meant to be shared between controllers must be a service. This is exactly what you want for your refresh function to be.
Whenever you inject the same factory into n controllers, you can't use the scope of every controller. This isn't the purpose of a controller.
However, whenever you inject the same factory into n controllers, you can use its exposed methods.
The problem you have, can be solved as follows:
app.factory( 'sharedFunctions', [ 'factoryId', function sharedFunctions( factoryId ) {
var refresh = function () {
factoryId.getAll(/*your params to query*/)
.success( function ( response ) {
//This will return the list of all your records
return response;
});
};
return sharedFunctions;
}]);
With this factory service registered, then you can inject it to your controllers and whenever you need to refresh, just call the exposed method of the service and plot the new information into the view.
Hope it works for you!
i ended up doing this:
I added in the list.contrl this:
factoryId.listScope = $scope;
since I already have the factoryId (my data service) injected in the detail controller, I can call this:
factoryId.listScope.refresh();
it works but I don't know if this is the best way. any comments?

Originzational MVC and Angular keeping from injecting what I don't need

My problem is I have one ng-app. Does that mean I have to do dependency injection for plugins I may not be using on that given view? Example I bring in ngTagsInput does that mean I have to do it even when the view doesn't call for it? That would mean I have to include that js for every view even if it doesn't use ngTagsInput.
I have a very large MVC .NET application and I am trying to figure out what is he best way to handle bringing in external plugins.
I have some code like so in our Main _Layout template:
<html ng-app="ourApp">
<head>
<!-- all of our includes are here -->
</head>
<body>
<directive></directive>
<anotherdirective></anotherdirective>
#RenderBody()
</body>
</html>
RenderBody is where MVC slides in our views from our mvc routing.That view may look like so:
<script src="~/Scripts/HomeAngular.js"></script>
<div ng-controller="HomeCtrl">
<directive3></directive3>
</div>
App JS:
var app = angular.module('ourApp', ['ngTagsInput']);
IS there a way I can get around having to inject ngTagsInput on every view page even if i don't need it?
There are several different ways to handle Dependency Injection (DI) in angular. In this first example, you simply define ngTagsInput before declaring the controller. If ngTagsInput is a service, for example, you'll need to return an object with methods that allow you to access the data inside of that service.
For example:
app.service('ngTagsInput', function($scope) {
var data = {};
return {
getData = function() {
return data;
},
setData = function(val) {
data = val;
}
};
});
app.controller('HomeCtrl', function($scope, ngTagsInput) {
// ...
$scope.tags = ngTagsInput; // whatever you want to do with it
});
However, there's a problem...
In the example above, if you run that code through a minifier, you'll get $scope turned into some variable (a, b, x, etc...) and angular wont know what to do with that.
In this method, we use an array. The last item in your array is your lambda function for the controller, which takes 1 argument for each previous item in the array:
app.controller('HomeCtrl', ['$scope', 'ngTagsInput', function(scp, ngTagIn) {
// ...
}]);
This code can be run through a minifier just fine, since the dependencies are strings in the array and can be renamed to anything you want inside the function's parameters.
DI also works in directives, factories, filters, and services with the same syntax; not just controllers and modules.
app.directive('HomeCtrl', ['$scope', 'ngTagsInput', function(scp, ngTagIn) {
// ...
}]);
Couldn't you break down your application further into smaller modules instead of just one. Then you can inject the smaller modules into the app module and only inject the ngTagsInput dependency on the modules that actually need it. That's how I typically break up my application by function or area.

Angular .Value not working

New to Angular and I am trying to figure out Value. I am trying to save a value that I can later inject into my controller but for some reason, it breaks. If you run the plnkr sample, it will work, code gets to the controller. If you comment out line 68 and un-comment 67, it breaks the application. Line 41, I just set a value which is what I want to pass into my controller.
Why would this not work?
http://plnkr.co/edit/SnOm2r?p=options
There is no AppConfig...if you want to inject AppConfig it has to exist somewhere, a directive, a service, a factory, SOMETHING. You don't currently have one being loaded.
Your issue is a timing issue. The controller is created before the value is set so it doesn't have access.
If you create like this:
var mainApp = angular.module("Test", ["ui.router"]);
mainApp.value("AppConfig", 1.0);
Then you can access it right away. If you have to set it asynchronously (i.e. you plan to set it as the result of a call) then the best way is probably to inject the $injector instead of the AppConfig. Then you can do:
if ($injector.has("AppConfig")) { value = $injector.get("AppConfig"); }
Even better may be to move that into a service with a promise that can return the value once it's fetched then cache it for subsequent calls.

angularJs - won't show data until user types in search field

Final Solution? It looks like I had my routing and controllers a little confused. I had my routing in a file with my controller module. I moved my routeProvider into the main module, like in the tutorial example. My controller and my routeProvider where under the same module. Maybe that was confusing everything. So now I have the controller in it's own module, and the routeProvider is under the main module. That seems to have fixed the problem without needing to initialize the search field to force the bindings to update the data.
Update:
The solution to showing my data at the time the page loads was to use an older version of angularJs, or use ng-Init and initialize the search field to a blank space.
I'm getting JSON data from the firebase website to update a table. I have a search field that works. The data will not display in the table until I type something into the search field. I don't know why the data won't just display in the table as soon as the controller is done getting the data.
Note: The link to the backend data is now removed, I don't want to keep that database file there indefinitely.
Here is the link to the jsFiddle code:
Last Version jsFiddle
Here is code for the controller.
'use strict';
/* App Module */
// Create the module named 'testApp'
var testApp = angular.module('theTestApp', [
'ngRoute',
'testServices'
]);
'use strict';
/* Services */
var testServices = angular.module('testServices', []);
testServices.controller('CommonController',
// function($scope, $http, $route) {
function($scope, $http) {
//access the customInput property using $route.current
//var dbKey = $route.current.customInput;
var dbKey = 'test-a-db-12345';
var urlToDb = 'https://' + dbKey + '.firebaseio.com/rows/.json';
$http.get(urlToDb).success(function(data) {
$scope.UsedItems = data;
});
});
How do I get the data to display as soon as it's loaded?
Update 1: I'm assuming that the data is already there, but the event of typing something into the search field triggers the filter, and then the data shows up. It shows up filtered.
Update 2: I'm reading about $Watch There is constantly and event loop listening for events. When a key is pressed in the search box, the bindings {{name}} get updated if something has changed. In this case, the content of the search input field was changed. So the issue seems to have something to do with when the bindings get updated, not whether the data is getting retrieved.
Update 3:
This version of the code runs. It loads the data when the page is rendered. Here is a working example in jsBins.
Update 4:
As of angularJs version 1.2.0 the behavior changes. Versions 1.0.8, 1.0.7 will instantly display my data when the page loads, 1.2.0 will NOT! I just happened to be using jsBins which uses 1.0.7, and it started working. Didn't know why until I started comparing the differences. Hopefully, there is a way to make it work in newer versions.
jsBins Working Example
The problem is that theSearch.Txt is empty. And you are filtering by that. My guess is that Angular at that moment decides to not let anything through and thus doesn't display anything.
What you should do:
Initialize the variable with a space filled string. (i.e. ' ')
Here is a working jsFiddle.
I used ngInit here. But that is because you decided to link?? the controller instead of putting it into a script tag. I suggest that next time you rather take the additional effort into pasting it in, as using the ngInit directive makes me feel like using eval.
Try
$scope.$apply(function(){
$scope.UsedItems=data;
}

Categories

Resources