How to hide an element while using a directive? - angularjs

I have made a directive in which a single template is using for three functions in a controller. The model for the fields are same. I want to hide a field if the directive is called third time.
<div class="active tab-pane " ng-if="linkid === '1'">
<mallsonline-product info="active_products"></mallsonline-product>
</div>
<!--Active products list ends here -->
<!-- Get Inactive Products -->
<div class="active tab-pane" ng-if="linkid === '2'" >
<mallsonline-product info="inactive_products"></mallsonline-product>
</div>
<!--Get most viewed products ends here -->
<div class="active tab-pane" ng-if="linkid === '3'" >
<mallsonline-product info="mostviewed_products"></mallsonline-product>
</div>
My controller looks something like this
mainControllers.controller('DashboardController', ['$scope', '$http', '$routeParams', '$cookies', '$rootScope', function ($scope, $http, $routeParams, $cookies, $rootScope) {
/* Getting all grid links */
$scope.grLinks = function (Id) {
console.log(Id);
$scope.linkid = Id;
};
/* Getting all grid links ends here */
/* Getting all active product list */
$scope.active_product = function () {
$http.get('js/active-products.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.active_products = data.items;
console.log($scope.active_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all active product ends here */
/* Getting all inactive product */
$scope.inactive_product = function () {
$http.get('js/inactive-products.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.inactive_products = data.items;
console.log($scope.inactive_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all inactive product */
/* Getting all most viewed products */
$scope.most_viewed = function () {
$http.get('js/most-viewed.json',
{headers:
{'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.mostviewed_products = data.items;
console.log($scope.mostviewed_products);
})
.error(function (data) {
console.log(data);
});
};
/* Getting all most viewed products */
$scope.active_product();
$scope.inactive_product();
$scope.most_viewed();
}]);
/* Active products / Inactive and most viewed Directive */
mainControllers.directive('mallsonlineProduct', function () {
return {
restrict: 'E',
scope: {
productInfo: '=info'
},
templateUrl: 'directives/dashboard_product.html'
};
});
/* Active products / Inactive directive ends here*/
and the template looks like this
<li class="bord-1-solid-ccc mg-bt-25" ng-repeat="active_products in productInfo">
<article class="aa-properties-item mg-top-0-notimp">
<a class="aa-properties-item-img" href="#/product">
<img alt="img" class="twohun-oneseventy" src="img/item/6.jpg">
</a>
<div class="aa-properties-item-content">
<div class="aa-properties-about padding-0-notimp">
<h5>{{active_products.name}}</h5>
<p class="font-size-11-imp"><i class="fa fa-building-o" aria-hidden="true"></i> {{active_products.mall.name}}</p>
<p class="font-size-11-imp"><i class="fa fa-map-marker" aria-hidden="true"></i> {{active_products.mall.address}}</p>
<p class="font-size-11-imp"><i class="fa fa-phone" aria-hidden="true"></i> {{active_products.shop.telephone}}</p>
<p class="font-size-11-imp"><i class="fa fa-eye" aria-hidden="true"></i> {{active_products.views}}</p>
</div>
</div>
</article>
</li>
all the fields are present in the model I want to show the active_products.view only when info="mostviewed_products". How can I achieve this ?

Had passed "linkid" in directive to know the current linkid value in template
Please make following changes
Directive
mainControllers.directive('mallsonlineProduct', function () {
return {
restrict: 'E',
scope: {
productInfo: '=info',
linkid:'=linkid'
},
templateUrl: 'directives/dashboard_product.html'
};
});
Html
<div class="active tab-pane " ng-if="linkid === '1'">
<mallsonline-product info="active_products" linkid="linkid"></mallsonline-product>
</div>
<!--Active products list ends here -->
<!-- Get Inactive Products -->
<div class="active tab-pane" ng-if="linkid === '2'" >
<mallsonline-product info="inactive_products" linkid="linkid"></mallsonline-product>
</div>
<!--Get most viewed products ends here -->
<div class="active tab-pane" ng-if="linkid === '3'" >
<mallsonline-product info="mostviewed_products" linkid="linkid"></mallsonline-product>
</div>
In template ('directives/dashboard_product.html')
<p class="font-size-11-imp"><i class="fa fa-eye" aria-hidden="true" ng-if="linkid==3"></i> {{active_products.views}}</p>
Hope this will resolve your issue.

Related

How do I open a modal from a controller using Angular-materialize

I am using Materialize CSS and the Angular-materialize directives:
http://materializecss.com/modals.html
http://krescruz.github.io/angular-materialize/#modals
I am trying to do the following
User clicks button
Controller action gets fired and we go get data from an api
Modal is displayed to user and data returned is displayed
I have the following button
<a href="#MyModal" modal class="my-modal-trigger waves-effect waves-green btn right"Show Data/a>
and modal
<div id="MyModal" class="modal">
<div class="modal-content center">
<div class="row">
<div class="row left">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class="card-title">Data</span>
</div>
<div>
<ul class="collection">
//loop the data
</ul>
</div>
</div>
<a class="modal-action modal-close waves-effect waves-green btn">Close</a>
</div>
</div>
</div>
</div>
and i have the following in my JS
var app = angular.module("MyApp", ['ngRoute', 'ui.materialize']);
How can i call a controller method to pop up the modal and fill it with data, from my controller
app.controller('mainController', function ($scope, $location, $http, AppConfig) {
var params = { some stuff}
$http({
method: 'POST',
url: myURL,
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function (data) {
//pop up the modal and show the data
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function (status) {
Materialize.toast('Bad stuff happened', 4000);
});
});
Angular-materialize lets you set an option open in your trigger. Use it to specify a variable that, when true, will launch your modal. Set it to false initially in your controller.
Use ng-click to call a function in your controller that fetches data from your API then sets the open variable to true on success.
Trigger:
<a href="#MyModal" class="btn" modal open="openModal"
ng-click="getDataOpenModal()">Show Data</a>
In Controller:
$scope.openModal = false;
$scope.getDataOpenModal = function() {
$http({
method: 'POST',
url: '/myUrl',
headers: {
'Content-Type': 'text/html',
'Accept': 'application/json'
},
params: params
})
.success(function(data) {
$scope.data = data;
$scope.openModal = true;
Materialize.toast('Awesome, we got the data', 4000);
})
.error(function(status) {
Materialize.toast('Bad stuff happened', 4000);
});
}
EDIT: There are two other options you can set in your trigger, ready and complete
HTML
<a href="#MyModal" class="btn" modal open="openModal"
ready="readyCallback()" complete="completeCallback()"
ng-click="getDataOpenModal()">Show Data</a>
JS
$scope.readyCallback = function() {
Materialize.toast("Modal ready", 4000);
}
$scope.completeCallback = function() {
Materialize.toast("Modal complete", 4000);
}
Worked for me with $scope.$apply() after $scope.openModal = true;
I was fighting with this too, but no solution worked for me. I had to change html side.
My html:
<i class="zmdi zmdi-eye"></i>
In controller:
$scope.openModal = false
$scope.get_info_log = function(){
$scope.openModal = true;
}
Data-target should match your modal id:
!-- Modal Structure-->
<div id="log_detail" class="modal modal-fixed-footer setup-modal">
<div class="modal-content">
</div>
</div>
<div class="modal-footer">
<a class=" modal-action modal-close waves-effect waves-light btn">Close</a>
</div>
</div>

Cannot extract all the "feed" information(Pictures) from facebook graph API

I am trying to extract information through facebook API into my ionic app. It shows the messages and dates correctly into my app but no images! I have uploaded the code and demo pictures in here.
Code:
.controller('FeedCtrl', function ($scope, $stateParams, OpenFB, $ionicLoading) {
$scope.show = function () {
$scope.loading = $ionicLoading.show({
content: 'Loading User Feed(s)...'
});
};
$scope.hide = function () {
$scope.loading.hide();
};
function loadFeed() {
$scope.show();
OpenFB.get('/me/feed', {
limit: 30
})
.success(function (result) {
$scope.hide();
$scope.items = result.data;
// Used with pull-to-refresh
$scope.$broadcast('scroll.refreshComplete');
})
.error(function (data) {
$scope.hide();
alert(data.error.message);
});
}
**[<!---ionic---->][1]**
<div ng-repeat="item in items" class="list card">
<div class="item item-avatar">
<img src="https://graph.facebook.com/{{ item.from.id }}/picture" />
<h2>{{item.name}}</h2>
<p>{{item.created_time | date:'MMM d, y h:mma'}}</p>
</div>
<div class="item item-body">
<p ng-if="item.story">{{item.story}}</p>
<p>{{item.message}}</p>
<h2>{{item.from.id}}</h2>
<img ng-if="item.picture" ng-src="{{item.picture}}" />
</div>
</div>
And

Not able to fetch data after refreshing dynamically created url in angular js application

I am new to angularjs and this my first post to stackoverflow. Iam trying to create small part of existing angular.
Iam trying to fetch dynamic url for "allproducts" page where url will have /allproducts/{corresponding city id}
My App.js looks like this:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/',
{
templateUrl: "view"
})
.when('/Cities',
{
templateUrl: "cities"
})
.when('/products',
{
templateUrl: "view/cities_products"
})
.when('/allproducts/:id',
{
templateUrl: "city/{id}/products"
})
.otherwise({
template: 'NOT FOUND'
})
});
and rest is defined inside a controller. This is to get city data
httpService.get(get_data_url3,"")
.then(function (result) {
if (result.status == 200) {
$scope.cities_data=result.data.data;
console.log($scope.cities_data);
}
if (result.status == 404) {
console.log("unauthorised");
}
}, function (status) {
console.log(status);
});
This is to get product data on click of corresponding city
$scope.allCityProducts = function(city,path)
{
$location.path('/allproducts/'+city.id);
var get_products_url=initial_url+"products/"+city.id;
$scope.selected_city=city;
httpService.get(get_products_url,"")
.then(function (result) {
if (result.status == 200) {
$scope.product_data=result.data;
}
if (result.status == 404) {
console.log("unauthorised");
}
}, function (status) {
console.log(status);
});
}
And html code for cities is below on whose click dynamic product url is being fetchd
<div class="view_context">
<br>
<div class="row table-heading">
<div class="column medium-4">Cities <i class="fa fa-map-marker"></i></div>
<div class="column medium-4">View Products <i class="fa fa-star"></i></div>
<div class="column medium-4"></div>
</div>
<div class="table-inside column medium-12" ng-repeat="city in cities_data">
<div class="column medium-4"> {{city.city_name}}</div>
<div class="column medium-4"><a style="color:black;" ng-click="allCityProducts(city,path)"><i class="fa fa-share-square" style="margin-right:10px"></i>VIEW</a></div>
<div class="column medium-4"></div>
</div>
and the product page is below
<div class="table-inside table-white column medium-12">
<div class="column medium-4">{{prod.product_name}}</div>
<div class="column medium-3">{{prod.product_price_city | currency:"₹ "}}</div>
<div class="column medium-3"><a style="color:black;" data-reveal-id="productModal" ng-click="editproduct(prod)"><i class="fa fa-pencil-square"></i> VIEW/EDIT</a></div>
<div class="column medium-2"><i class="fa fa-trash" ng-click="deleteproduct(prod,selected_city.id,$index)"></i></div>
</div>
All works well except when dynamically created product page is reloaded no data is being fetched because httpservice is working on ng-click="allcityproducts". where city id is passed. What can be done to sort this??
For fetching a template based on the city id ,you could have templateUrl function instead of using URL string directly. templateUrl function will have 1st parameter(here its params) which will have route parameter object.
Code
templateUrl: function(params){
return "city/"+ params.id +"/products"
}

Can't display ng-repeat child scope property

I need to display a list of data records using ng-repeat. Within every data object entry (a coupon) displyed, I need to grab some properties ($scope.etabName and $scope.etabDistance) from that object, do some calculations and show the result in the same data object's view within the ng-repeat view.
I've managed to do the calculations and when I console.log them the results are correct, but they are not showing correctly: the property displyed is the one relative to the last data object iterated by ng-repeat.
I know I'm not understanding the Angular way of doing scopes, so any help is welcome.
My controller:
$scope.getCouponList = function () {
$http({
method: 'JSONP',
url: $scope.couponListUrl + "?callback=JSON_CALLBACK&cookie=" + $localStorage.user.cookie +
"&usr_latitude=" + $rootScope.lat + "&usr_longitude=" + $rootScope.lng
}).
success(function (data, status) {
if (data.status && data.status == "ok") {
$rootScope.couponList = data.list;
}
}).error(function (data, status, headers, config) {
});
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$scope.etabName = etab.name;
$scope.etabDistance = etab.distance;
}
});
};
};
My view:
<ion-content scroll="true" ng-controller="getCouponList">
<ion-list>
<ion-item class="decline" ng-repeat="coupon in couponList"
ng-click="fetchCouponDetails(coupon)"
ng-init="fetchEtabDetails(coupon)">
<div class="offer-image">
<img class="full-image" ng-src="{{coupon.image_operation}}">
<div class="offer-logo">
<img ng-src="{{coupon.enseigne_logo_url}}">
</div>
<div class="offer-ens-name">
<span>{{coupon.ens_name}}</span>
</div>
<div class="offer-name wrap-txt">
<span>{{coupon.name}}</span>
</div>
<div class="offer-deadline-details">
<i class="icon ion-android-time"></i>
<timer countdown="coupon.diff_date" max-time-unit="'year'" interval="1000">{{ddays}}:{{hhours}}:{{mminutes}}</timer>
</div>
<div class="offer-zone">
<i class="icon ion-location" class="etab"></i>
<span>{{etabName}} {{etabDistance}} km</span>
</div>
</div>
</ion-item>
</ion-list>
</ion-content>
In this function:
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$scope.etabName = etab.name;
$scope.etabDistance = etab.distance;
}
});
You only have 1 $scope.etabName. Each call is overwriting it.
I would do this...
$scope.fetchEtabDetails = function($stateParams) {
_.select($stateParams.etablissement, function (etab) {
if (etab.id === $stateParams.etabcloser) {
$stateParams.etabName = etab.name;
$stateParams.etabDistance = etab.distance;
}
});
then in your HTML...
<div class="offer-zone">
<i class="icon ion-location" class="etab"></i>
<span>{{coupon.etabName}} {{coupon.etabDistance}} km</span>
</div>

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Resources