I have home page it contains with list of 2 images i have given controller and Html code.every time home page images loading from backend i want to cache the image in local to avoid every time http request and weekly once or 10 days once i want to check from backend if backend image has changed that time i need to update this cache image . i have followed some example but i could not solve this because i am new to this technology some one help me out to move forward
.controller('TestCtrl', [
'$scope', '$http', '$location', '$window', '$ionicLoading',
function($scope, $http, $location, $window, $ionicLoading) {
$scope.find = function() {
$http.get('****').success(function(data, status, headers, config, response) {
$scope.image1 = data[0].Images1;
$scope.image2 = data[1].Images2;
})
}
}
])
<ion-view title="Home" data-ng-controller="TestCtrl" data-ng-init="find()">
<ion-content>
<div class="list card">
<div class="item item-image">
<img src="{{image1}}">
</div>
</div>
<div class="list card">
<div class="item item-image">
<img src="{{image2}}" >
</div>
</div>
</ion-content>
</ion-view >
console i am getting
image1:http://res.cloudinary.com/dl34322/image/upload/q_58/v1437810617/store1.png
image2:http://res.cloudinary.com/dl34322/image/upload/q_58/v1437810617/store2.png
Just save them in local storage, then when the app loads up if there aren't any images in local storage (first time getting the app or it got wiped for some reason) fetch the images.
set it like this:
localStorage.setItem("image1", $scope.image1);
fetch it like this:
$scope.image1FromLocalStorage = localStorage.getItem("image1");
Then every 10 days or whatever you want you can fetch new images from the backend and save them to local storage.
If you don't want to implement all the rest yourself (like LRU or cache size limit and so on) you may want to consider a more complete solution Here are 2 options:
Generic Ioinc Cache: https://github.com/Nodonisko/ionic-cache
Another kind of cache which may be more apropriate for images: https://github.com/BenBBear/ionic-cache-src
See this: ionic 2 caching images
Related
I've gone through other questions, but couldn't find any that dynamically loaded controllers/views the way I am. I still fear this may be a duplicate question, but I have done my due diligence and came up empty. Please point me in the right direction if you're better with search terms.
This is how my app works: My index page loads up RequireJS pointing to a main.js file which outlines the initial includes (app.js, routeResolver, and a data service (unused currently). The routeResolver allows me to dynamically load in my views and respective controllers using code such as below within app.js. (Using a consistent naming convention, passing 'home' loads in home.html and associates it with homeController.js from their respective controllers/views locations.) We do not need to use ng-app='appname' because it’s added at runtime by calling angular.bootstrap() within the app.js file.
//Define routes - controllers will be loaded dynamically
var route = routeResolverProvider.route;
$routeProvider
.when('/', route.resolve('home'))
.when('/createnew', route.resolve('createnew'))
In my controller, I'm loading a variable from sessionStorage. (I have confirmed it is there/available. The test alert displays it correctly.) My problem is it is not displayed on the html page, and the console does not produce any errors. I have confirmed the page is accurately associating itself with the controller because if I remove the expression, I get an error that it is not defined... but despite it containing a value, it still doesn't display. All I get is 'Welcome '.
Controller:
'use strict';
define(['app'], function (app) {
var injectParams = ['$location', '$filter', '$window', '$timeout'];
var homeController = function ($location, $filter, $window, $timeout) {
var userTitle = sessionStorage.getItem('userTitle');
alert(userTitle);
};
homeController.$inject = injectParams;
app.register.controller('homeController', homeController);
});
View:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-sm-2 sidenav">
<p>Placeholder</p>
</div>
<div class="col-sm-8 text-left">
<p>Welcome {{ userTitle }}</p>
</div>
<div class="col-sm-2 sidenav">
<div class="well">
<p>Placeholder</p>
</div>
<div class="well"></div>
</div>
</div>
</div>
I'll gladly share more code, but I didn't want to make this too long and I feel like I'm just missing something silly...
At first glance, I noticed you're making a local variable named userTitle when you want to add that variable to $scope.
Inject $scope into homeController and $scope.userTitle = 'test';. This should get you what you want.
I am using Angular 1.5.7 and am trying to see if I can push the value of an attribute within a directive used on several different pages to an array that lives in the controller.
I am pretty sure that I need to used transclusion in order to do this but I am stuck. Below is a simplified version of what I have so far:
about.html
<div ng-controller="MainCtrl as ctrl"
<div cd-header mypage="About">
<div>About Page</div>
</div>
</div>
contact.html
<div ng-controller="MainCtrl as ctrl"
<div cd-header mypage="Contact">
<div>Contact Page</div>
</div>
</div>
header.html
<div>{{mypage}}
<div ng-transclude></div>
</div>
cd-header.js
var cdHeader = function() {
return {
scope: {
mypage: "#"
},
transclude: true,
templateUrl: 'header.html',
link: function(scope) {
// Not sure but I think I might need a function here
}
}
}
module.exports = cdHeader;
MainCtrl.js
var MainCtrl = function($scope) {
var nav = [];
// Not sure how items that are pushed to the nav get to this point
}
module.exports = MainCtrl;
main.js
var app = angular.module("myapp", [
'about',
'contact',
])
.controller('MainCtrl', MainCtrl)
.directive('cdHeader', cdHeader)
I am able to get the value of the mypage attribute in the directive as well as its transcluded <div> to appear in the header but only for the current page in view.
The part I am missing is how to get all of the mypage values from each page into the header regardless of the current page in view. I am somewhat new to Angular and have read a lot but have not come across anything that explains how this can be done. Maybe this is achieved with a service? If so, I'm not sure how to go about it.
To clarify with a visual. This is what I see:
But this is what I want to see:
As you rightly pointed out, there are several ways to do it.
Perhaps you can pass the array from the MainCtrl as an attribute to the directive. For instance, nav-array="nav". However, before that, you need to set the array nav as such
var $scope = this;
this.nav = [];
The second option is to consume a service. Create an angular service, pass it as a dependency in the directive, and consume it.
Lets create an array in MainCtrl as $scope.headers = ['about':'About','contact':'Contact','home':'Home'] or create a factory/service to share the headers data and in header.html use ng-repeat to display the header name according to myPage value like below
<div ng-repeat="page in headers[myPage]">{{page}}
<div ng-transclude></div>
</div>
I want to change the color item whan my data change. I use this template code:
<ion-view view-title="Evénement" class="content">
<ion-content class="padding">
<ion-list>
<ion-item ng-repeat="myuser in users">
<span>{{myuser.user_name}} </span><a class="button button-icon icon ion-person-add icon_add" ng-click="addContact('{{myuser.id}}')" ng-class="{contact_added : myuser.isContact }"></a>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
I use firebase to loading and saving data. So, I use this code for synchronizing data.
ref.child('contact').child(authData.uid).on('child_added', function (snapshot) {
var myUser = snapshot.key();
$scope.users.push(myUser);
});
When I add a contact on firebase, my color icon does not change immediately. I must click and move my mouse on html page to update the color.
How I have to do to refresh instantly my icon when the data change?
Don't use $scope.$apply(), use AngularFire.
Angular apps should not have to manage the digest loop. Firebase directly integrates with Angular with the AngularFire library, which manages data synchronization and the triggering of $digest.
In your case you can create a $firebaseArray to synchronize your changes:
angular.module('app', ['firebase'])
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController);
function MyController($scope, rootRef, $firebaseArray) {
var userRef = rootRef.child('contact').child(authData.uid);
$scope.users = $firebaseArray(userRef);
}
The advantage of using AngularFire is two fold. Firstly, you don't have to manage $scope.$apply(). Secondly, you get realtime array synchronization for free.
add $scope.$apply(); after $scope.users.push(myUser); line.
I'm trying to make a blog using AngularJS. The home page queries a third party service of mine that returns an array of all my articles/posts. I am displaying shortened versions of these posts on the home page, and want to have "read more" under each post that passes that post's ID through a URL parameter to another HTML page:
index.html:
<div ng-controller="blogCtrl" id="blog">
<div class="post" ng-repeat="post in posts">
<div class="header">
<h1>{{ post.fields.title }}</h1>
<p class="date">{{ post.sys.createdAt | date}}</p>
</div>
<p>{{ post.fields.body | cut:true:1600:' ...'}}</p>
read more
</div>
</div>
What do I need to do in post.html so that I can read the value of id in the URL parameter? Do I need to create a new angularJS app in post.html?
edit:
I've changed the read more link to <a href="post/{{post.sys.id}}"> and i am trying to set up the following route:
app.config(function($routeProvider){
$routeProvider
.when('/post/:postid',{
templateUrl: '/post.html',
controller: 'postCtrl'
})
});
However, clicking the "read more" link doesn't load up post.html, but instead a page that says File not found: /post/2B1K9K2DHqsYaGYcms2YeW. The route doesn't seem to be getting properly set up, since post.html isn't getting loaded.
This isn't all that hard to do, but you need to have routing set up on your app. You can create this functionality in your existing app, or separate it into a new one, it's up to you. Here are the relevant things you'll need to include in your code:
In your app include ngRoute as a dependency:
var myApp = angular.module('myApp', ['ngRoute']);
Also include routing config for your app:
myApp.config(function($routeProvider){
$routeProvider
.when('/someroute', {
templateUrl: 'someFolder/withSomeFile.html'
}
.when('/someroutewithparamters/:aftercolonisparameter', {
templateUrl: 'someFolder/post.html'
}
});
You can include a default route as well, but it's not necessary if you'd rather not. Be sure to include angular-route.js in your index.html for this to work.
Now in your controller you can simply do something like:
myApp.controller('postCtrl', function($routeParams, $scope, postFactory){
$scope.post = postFactory.functionToLoadPost($routeParams.aftercolonisparameter);
});
Obviously this will be different for your implementation based on how everything is set up, and you'll probably want to pick better names for your elements than I did, but those are the things you'll need in place to make this work. It's actually pretty straightforward.
I have an angularjs-Application.
In one Controller i´m waiting for an image source address - I get this from an PHP-Service.
controller.controller("LayoutCtrl",
["$scope", "$http", "$route",
function($scope, $http, $route) {
$scope.$route = $route;
$http.get('zkLib/services/header.php').success(function(data) {
$scope.header = data; });
}]);
The header.php looks like this:
$result = array();
$result['index'] = db()->loadSetting('index_page');
$result['banner'] = db()->loadSetting('site_banner');
echo json_encode($result);
So in my template i´ve written:
<div ng-controller="LayoutCtrl">
<div desc="header">
<a desc='hp_link' href="#{{header.index}}">
<img desc='banner' ng-src="zkLib/f/img/{{header.banner}}">
</a>
</div>
</div>
My Problem is now:
When the site opens, it shows the "NoImage"-Icon from the Browser while waiting for this service.
After this the image will be viewed correctly.
But in my COnsole i have this error too:
Resource interpreted as Image but transferred with MIME type text/html: "http://localhost:160/cms/app/zkLib/f/img/".
On my Server i have the image 'loading.gif', i want to show this while i´m waiting for my service.
How to solve this? Could someone help?
The reason you are getting the error in the console is because, before the request to header.php completes and angular renders {{header.banner}}, its trying to load just "zkLib/f/img/". You can fix this by putting the entire relative url into the {{header.banner}} scope property.For example...
<img desc='banner' ng-src="{{header.banner}}">
and make header.banner be the full relative path...
$http.get('zkLib/services/header.php').success(function(data) {
$scope.header = data;
$scope.bannerImage = 'zkLib/f/img/' + $scope.header.banner;
});
Now, before the request is complete, the image src will be an empty string and it won't show the broken image icon or throw the error. If you want to show a loading image before the controller loads, you can just set src, like this...
<img desc='banner' ng-src="{{bannerImage}}" src="/path/to/loading.gif">
Before the request is complete, the src will be the loading.gif file. Once the request completes, ng-src will kick in and your header.banner image will be displayed
When the controller is instantiated, $scope.header is still empty.
This makes ng-src="zkLib/f/img/{{header.banner}}" to be evaluated to this relative path:
'zkLib/f/img/' // translates to "http://localhost:160/cms/app/zkLib/f/img/"
What you need to do is to keep ng-src empty while $scope.header is empty.
#1) One way is to write this:
<img desc='banner' ng-if="header" ng-src="zkLib/f/img/{{header.banner}}">
#2) Or this (if you don't want to use ngIf):
<img desc='banner' ng-src="{{ header && 'zkLib/f/img/' + header.banner }}">
#3) But I would prefer to create the link inside the controller:
$http.get('zkLib/services/header.php').success(function(data) {
$scope.header = data;
$scope.banner = 'zkLib/f/img/' + data.banner;
});
And then just use it easily:
<img desc='banner' ng-src="{{ banner }}">