I am new in angular js. I am working with web Sql in a test project for learning purpose. My insert operation is working fine. My problem is when i fetch all the records then i can't store it in $scope.todos=results.rows
My code is
tx.transaction(sql,[],myCallback)
function myCallback(tx,results)
{
console.log(results.rows); // shows objects in console
$scope.todos=results.rows;
}
In view the todos is not working with ng-repeat.
It might help to show all of your controller, or service. If it's a controller make sure you included the $scope parameter for example:
.controller('MyController', function ($scope){
}))
If you are doing this inside a service, save it in a variable inside the service, then from a controller where the "$scope" is available include your service then call your variable containing the results. This will also be helpful if you need to share those results with other controllers at a later time.
.service('MyDataService',function(){
var todos;
return {
.... set and get functions to access variable ...
getTodos: function() {
return todos;
}
};
});
And in controller
.controller('MyController', function ($scope, MyDataService){
$scope.todos = MyDataService.getTodos()
}))
There are also ways to get the $scope working in a service but I don't think it's a great idea.
Related
Hello Angular experts,
I have to preload a certain dataset (factory call to the database) to the controller. I don't use angular views so stateProvider or routeProvider cannot be used to resolve. Basically I need the dataset readily available before loading the controller.
Is there a way to achieve this?
I have a controller and a view. The view also has a widget. The widget has an attribute that expects a dataset. By the time the controller is done fetching data the view is already rendered so the widget input parameters are empty. So I need the widget dataset to be filled much before getting to the controller. By the way the app.run solution doesn't work as there is a promise involved.
You can't say as before loading controller, i correct it with before binding controller
angularjs has app.run and i think you know it, it work just when application run (first time) and every time you refresh it.
var app = angular.module("app", []);
app.run(function($http, $rootScope) {
$http.get("url").then(function(response){
console.log(response.data)
$rootScope.data = response.data; // as global scope
})
})
app.controller('ctrl', function($scope) {
$scope.$watch('data', function(newValue, oldValue) {
if(newValue){
console.log(newValue) // you will get `rootscope.data` when it's ready
}
})
})
You can add factory to the app run too.
please fill free to ask question.
Based on your comment, what you are trying to do shouldn't require any changes to the Controller.
What you are actually trying to do is delay rendering of the widget component until you have data that the widget needs. This is commonly handled by ng-if in your HTML.
For Example (pseudocode):
<div ng-if="myData">
<Widget input="myData"></Widget>
</div>
Angular will not render this div until myData has a value, and all your Controller has to do is make sure myData is added to $scope.
At first I searched a lot about this question, used some suggestions but couldn't get results.
I had one js file, main.js, where there was only one controller and everything worked fine:
var app = angular.module('monitoringApp', ['ui.bootstrap', 'ngCookies', 'angularCharts','angularUtils.directives.dirPagination','ngLoadScript','ngRoute','dragtable']);
app.controller('mainController', ['$scope', '$http', '$cookies', '$cookieStore' , '$location', function($scope, $http, $cookies, $cookieStore,$location) {
//some function which i need to call;
}
I've added a library for drag and drop table columns dragtable.js and inside dragEnd() function I want to call some function inside main.js
var project = angular.module("dragtable", []);
project.directive('draggable', function($window, $document) {
function dragEnd($event) { need to call function inside main.js }
}
Please note that I already tried to use shared service but still getting error undefined on the function which is called.
It doesn't really matter in which file you're storing the functions. That said, a directive is unlikely to be what you're looking for as a directive is mainly used to be linked to an html element like a widget. Think of it as the controller in the MVC model scheme. It where you can have interaction from/to the ui from the coding standing point. But you can't really call a directive function directly if you don't have access to a directive.
A service on the other hand is just a singleton object that can be injected in a controller or in other places.
What you want is probably this:
project.factory('draggable', function () {
function dragEnd($event) { ... }
return dragEnd
})
And inside your main module:
app.controller('mainController',
[
'$scope'
, '$http'
, '$cookies'
, '$cookieStore'
, '$location'
, 'draggable'
, function(
$scope
, $http
, $cookies
, $cookieStore
, $location
, draggable
) {
//here you can call draggable
}]
)
Here you can see that the draggable function aka dragEnd is injected in the controller. This is good if you want to use this common function for multiple handler but then you might need to bind the function to an object like this:
var draggable = draggable.bind(someobj)
Or use it with apply or call
draggable.call(someobj, event)
draggable.apply(someobj, [event])
The reason to do that is that if you want to acces this from within the function when it's called, it might not be what it you expect it to be depending on how you're actually calling the method.
Also one note regarding your directive... You always have to return something. In you case chances are that you created the factory but didn't return anything. For this reason you had the "undefined" error. If you don'T return anything the factory will create and delete the function when it's run.
I am making a page that is extracting some information from the server and showing it on the interface. I am using angular js for this. So I have made a controller that has $http.get() method which gets data from the server and then the data binding is used to bind data to the html page. I am using this controller...
mission_vision_mod.controller('mission_visionCtrl', ['$scope','$http', function($scope, $http) {
$scope.visiontext = "Here is the content of vision";
$scope.bkclr = ['bk-clr-one','bk-clr-two','bk-clr-three','bk-clr-four'];
$scope.progressbar = ['progress-bar-warning','progress-bar-danger','progress-bar-success','progress-bar-primary'];
$scope.missioncount = ['col-md-0','col-md-12','col-md-6','col-md-4','col-md-3','col-md-2.5','col-md-2'];
$http.get('m_id.json').success(function(data){
$scope.missions = data;
$scope.len = data.length;
});
}]);
Now i want to make a page that allows the users to edit this info, this page also requires the same above code (code inside the controller). I also have to make a different controller for the new page to send whatever data that has been edited to server.
How do i use the above code for both the pages while i have to make a new controller for the second one for editing purpose. I want to use the same code for both the controllers.
I would suggest moving that code to a Service, then inject and use that service in each of the controllers where you need this functionality.
Services are often the best place to add code that is shared between multiple controllers or if you need a mechanism to pass data betweeen controllers.
Hope this helps!
Service/factory/value are meant for this , please refer the below example hope you get a better idea .
var app = angular.module('myApp',[]);
//controller
app.controller('myCtrl',myCtrl);
//inject dependencies
myCtrl.$inject = ["$scope","httpService"];
function myCtrl($scope,httpFactory){
$scope.data = httpFactory.getData;
}
//factory : http factory
app.factory('httpFactory',httpFactory);
//inject dependencies
httpFactory.$inject = ["$http"];
function httpFactory($http){
var datas = [];
return {
getData:function(){
$http.get('url').success(function(data){
datas.push(data);
}).
error(function(){
console.log('error');
});
return datas
}
}
}
I´m trying to code a CRUD app with Angular.JS, and I need your help to move on.
This is the scenario:
View 1 (index) gets JSONP data from a remote API and stores it.
View 2 (master) shows data filtered on a grid
View 3 (detail) shows an specific item selected on View 2
I did it already, but requesting the very same JSON object on each view, , but I think one only api call is enough.
I can´t figure out how to properly share this JSON object for all the controllers. I tried several tutorials on ngResource, $http, factories and services but still have not a clear path to go through.
How can I do this?
Any snippet or code sample you may share will be very useful to keep on tryin this thing...
Thanks in advance,
Ariel
You can implement a base controller to store common functionality that's shared between the controllers. I wrote a blog post about it recently, here's the code snippet showing how it works:
'use strict';
angular.module('Diary')
// base controller containing common functions for add/edit controllers
.controller('Diary.BaseAddEditController',
['$scope', 'DiaryService',
function ($scope, DiaryService) {
$scope.diaryEntry = {};
$scope.saveDiaryEntry = function () {
DiaryService.SaveDiaryEntry($scope.diaryEntry);
};
// add any other shared functionality here.
}])
.controller('Diary.AddDiaryController',
['$scope', '$controller',
function ($scope, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
}])
.controller('Diary.EditDiaryController',
['$scope', '$routeParams', 'DiaryService', '$controller',
function ($scope, $routeParams, DiaryService, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
DiaryService.GetDiaryEntry($routeParams.id).success(function (data) {
$scope.diaryEntry = data;
});
}]);
Using services to cache and share the data across controllers would be the way to go. Since services in angular are singleton, the same copy of data can be shared. A service such as
angular.module('myApp').factory('dataService', function($q, $resource) {
var items=[];
var service={};
service.getItems=function() {
var itemsDefer=$q.defer();
if(items.length >0)
itemsDefer.resolve(data);
else
{
$resource(url).query({},function(data) {
items=data;
itemsDefer.resolve(data)
});
}
return itemsDefer.promise;
}
return service;
});
Now in the controller you can inject the dataService and call the getItems method. This method returns a promise, which is either resolved using the cached data or by making remote request.
And the controller code would look something like
angular.module('myApp').controller('MyCtrl', function($scope,dataService) {
dataService.getItems().then(function(items) {
$scope.items=items;
}
});
What is correct way of passing variables from web page when initializing $scope?
I currently know 2 possibilities:
ng-init, which looks awful and not recommended (?)
using AJAX request for resource, which requires additional request to server which I do not want.
Is there any other way?
If those variables are able to be injected through ng-init, I'm assuming you have them declared in Javascript.
So you should create a service (constant) to share these variables:
var variablesFromWebPage = ...;
app.constant('initValues', variablesFromWebPage);
With this service, you don't need to add them to the scope in the app start, you can use it from any controller you have, just by injecting it (function MyCtrl(initValues) {}).
Althouhg, if you do require it to be in the scope, then this is one of the main reasons what controllers are meant for, as per the docs:
Use controllers to:
Set up the initial state of a scope object.
Add behavior to the scope object.
Just add this cotroller to your root node:
app.controller('InitCtrl', function($rootScope, initValues) {
$rootScope.variable1 = initValue.someVariable;
$rootScope.variable2 = initValue.anotherVariable;
});
#Cunha: Tnx.
Here some more details how I did it:
In the Webpage:
<script type="text/javascript">
var variablesFromWebPage = {};
variablesFromWebPage.phoneNumber = '#Model.PhoneNumber';
</script>
In the angular application file, registering the service:
var module= angular.module('mymodule', ['ngRoute', 'ngAnimate']);
module.factory('variablesFromWebPage', function () {
return variablesFromWebPage
});
And then the controller:
module.controller('IndexController',
function ($scope, $location, $http, $interval, variablesFromWebPage) {
$scope.phoneNumber = variablesFromWebPage.phoneNumber;
}
);