How to bind value from controller for ionic radio - javascript

Im trying to bind value of radio button from ionic controller. The following is the code i have used for.
<div class="list">
<ion-radio ng-model="SearchChoice" ng-value="All" ng-click="SearchByFilter('All')"> ALL <div id="badge-all" class="count-jkt"> <span ng-bind="AllCount.OnGoing"></span></div></ion-radio>
<ion-radio ng-model="SearchChoice" ng-value="New" ng-click="SearchByFilter('New')"> NEW <div id="badge-new" class="count-jkt">{{AllCount.New}}</div></ion-radio>
</div>
and my controller is,
.controller('MainCtrl', function($scope) {
$scope.SearchChoice = "All";
$scope.SearchByFilter = function(item) {
console.log( "Filter:", item);
};
});
Here the value is not binding properly. Kindly help me guys!

Could you try it using the . notation ?
<div class="list">
<ion-radio ng-model="model.SearchChoice" ng-value="All" ng-click="SearchByFilter('All')"> ALL <div id="badge-all" class="count-jkt"> <span ng-bind="AllCount.OnGoing"></span></div></ion-radio>
<ion-radio ng-model="model.SearchChoice" ng-value="New" ng-click="SearchByFilter('New')"> NEW <div id="badge-new" class="count-jkt">{{AllCount.New}}</div></ion-radio>
</div>
.controller('MainCtrl', function($scope) {
$scope.model = {
SearchChoice: "All"
};
$scope.SearchByFilter = function(item) {
console.log( "Filter:", item);
};
});
For more info about the . notation see here.

Related

How to display a returned json in angular view?

I am implementing a search in the github repository.
I need to display the information that i get from here: https://api.github.com/search/repositories?q=bootstrap . for instance into a view or HTML
<div ng-app="newsearchApp">
<div ng-controller="MainCtrl">
<form action="#/about" method="get">
<input ng-model="searchText" />
<button ng-click="search()">Search</button>
</form>
</div>
</div>
the code for searching the Github repository;
angular.module('newsearchApp')
.controller("MainCtrl", ["$scope", function($scope) {
$scope.searchText = "";
$scope.search = function() {
console.log($scope.searchText);
var item = $scope.searchText;
// console.log(item)
var GithubSearcher = require('github-search-api');
var github = new GithubSearcher({username: 'test#something.com', password: 'passwordHere'});
var params = {
'term': $scope.searchText
};
//i am not certain about the 'userData'
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data; //i am not certain about the 'repoData'
});
} }]);
the problem is here, when populating the json object to HTML
<div ng-repeat="repo in userData | filter:searchText | orderBy:predicate:reverse" class="list-group-item ">
<div class="row">
<div class="col-md-8">
<h4>
<small>
<span ng-if="repo.fork" class="octicon octicon-repo-forked"></span>
<span ng-if="!repo.fork" class="octicon octicon-repo"></span>
<small>{{repo.forks_count}}</small>
</small>
<a href="{{repo.html_url}}" target="_blank" >
{{repo.name}}
</a>
<small>{{repo.description}}</small>
<small>{{repo.stargazers_count}}</small>
<a href="{{repo.open_issues_count}}" target="_blank" >
Open Issues
</a>
<small>{{}}</small>
</h4>
</div>
</div>
</div>
the results are null on the HTML but are not null on the console.
thanks in advance
the results are null
The problem is, that Angular doesn't notice that the GitHub server has answered and doesn't update the view. You have to tell Angular manually to re-render the view. Try calling $scope.$apply():
github.searchRepos(params, function(data) {
console.log(data);
$scope.userData = data;
$scope.$apply();
});
If you'd make your request to the GitHub API with Angulars $http service, then this would not be needed - you'll only need $scope.$apply() if something asynchronous happens which doesnt live in the "Angular world" - for example things like setTimeout, jQuery ajax calls, and so on. That's why there are Angular wrappers like $timeout and $http.
More details: http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
The GitHub API can be accessed using the AngularJS $http service:
app.controller("myVm", function($scope,$http) {
var vm = $scope;
var url = "https://api.github.com/search/repositories?q=bootstrap"
$http.get(url).then(function onSuccess(response) {
vm.data = response.data;
console.log(vm.data);
})
})
HTML
<div ng-app="myApp" ng-controller="myVm">
<div ng-repeat="item in data.items">
{{item.full_name}}
</div>
</div>
The DEMO on JSFiddle
Since you're not using the Angular $http service, angular is not aware of the changes. You need to manually tell Angular to re-render and evaluate by using
$scope.$apply();

how to change the content of a single div in ng-repeat

I have this angular code.
<div ng-repeat="item in items | filter:search" class="container">
<h3>{{item.name}}</h3>
<p>category:{{item.category}}</p>
<p>price:INR {{item.price}} /-</p>
<br/>
<button ng-hide="showme" ng-click="process(item.name,item.price)">Add</button>
<button ng-show="showme" class="ng-cloak">Remove</button>
</div>``
Now what I want is whenever I click on the add button in one the div that button should hide and a remove button should display. I am able to do that but all the div are changing. I want to change just that div for which the button is clicked.
Here's my controller code
var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
$http.get('apna.json').success(function (data){
$scope.items = data;
});
$scope.showme=false;
$scope.process = function(name,value){
$scope.total = parseInt($scope.total) + parseInt(value);
$scope.showme = true;
}
});
you can assign a showme field to your items array , and give it a value to false , and in the ng-show and ng-hide directive use item.showme . Similarly in process() change the showme variable related to that item
Your showme variable is on $scope, so each item does not get a new showme variable/property to hold its individual setting. So instead of putting it on $scope you can just set a new property on item itself indicating wither or not it was added. You then use that to test in your ng-show/hide.
<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>
And in your process method
item.added = true;
Demo
var myApp = angular.module('myApp',[]);
myApp.controller('restaurantController', function($scope, $http){
$scope.items = [
{name:"Item 1",category:"food",price:19},
{name:"Item 2",category:"auto",price:39},
{name:"Item 3",category:"software",price:13}
];
$scope.total = 0;
$scope.process = function(item){
$scope.total = parseInt($scope.total) + parseInt(item.price);
item.added = true;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="restaurantController">
Total: {{total}}<br>
<div ng-repeat="item in items | filter:search" class="container">
<h3>{{item.name}}</h3>
<p>category:{{item.category}}</p>
<p>price:INR {{item.price}} /-</p>
<br/>
<button ng-hide="item.added" ng-click="process(item)">Add</button>
<button ng-show="item.added" class="ng-cloak">Remove</button>
</div>
</div>

How do I increment a counter when clicking an item in an ng-repeat?

I have generated a list with ng-repeat, where each item has a count variable. In each list item I have a link.
I want to increment the count when I click the link.
I tried the following way but it not work.
My Controller :-
myApp.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
function ctrl($scope) {
$scope.increment = function(item){
item.count += 1;
}
}
})
and view like :-
<ion-content class="padding" lazy-scroll>
<div class="row no-padding HomeRowsList">
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
<div class="countbg">عدد المرات : {{post.custom_fields.azkarno}}</div>
<span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>
</div>
</div>
</div>
</div>
</div>
</ion-content>
In controller use
$scope.increment = function(item){
item.count += 1;
};
instead of
function ctrl($scope) {
$scope.increment = function(item){
item.count += 1;
}
}
and in html use
<span>{{post.count}}</span><a data-ng-click="increment(post)">Increment</a>
instead of
<span>{{post.count}}</span><a onclick="ctrl(post);">Increment</a>
It should be ng-click instead of onclick & the method name should be increment instead of ctrl.
Also remove unnecessary ctrl function wrapper from the increment method which is not needed at all, because whatever you wanted to call from the html should be included in the $scope of controller.
Markup
<span>{{post.count}}</span><a ng-click="increment(post);">Increment</a>

AngularJS directive - ng-class in ng- repeat should it be a $watcher to toggle style?

I am currently implementing a spike to further my understanding on angular directives etc.
The premise is to create a FX watch list on a number of currency pairs.
My data feed is set up for my price updates via socket.io.
The stumbling block that i have is being able to change the css dependent on price change ie up arrow for up, down arrow for down.
I feel a watcher function is what i need but struggled on where to start so was looking for some sort of expression in ng-class to do the job ... but the method not only started to look like a $watcher it was also flawed as saving the previous price to scope on my directive meant there was only ever one old value not one for each price.
There for my question is : Is the solution with ng-class or in setting up a $watcher function ?
Heres my code ...
HTML template
<div ng-repeat="rate in rates" ng-click="symbolSelected(rate)">
<div class="col-1-4">
{{rate.symbol}}
</div>
<div class="col-1-4">
<span ng-class='bullBear(rate.bidPoint)' ></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
<div class="col-1-4">
<span ng-class='bullBear(rate.offerPoint)' ></span> {{rate.offerBig}}<span class="point">{{rate.offerPoint}}</span>
</div>
<div class="col-1-4">
{{rate.timeStamp | date : 'hh:mm:ss'}}
</div>
</div>
My directive currently looks like this ... as noted this will not work and the bullBear method was starting to look like a $watcher function.
.directive('fxmarketWatch', function(fxMarketWatchPriceService){
return {
restrict:'E',
replace:'true',
scope: { },
templateUrl:'common/directives/fxMarketWatch/marketwatch.tpl.html',
controller : function($scope, SYMBOL_SELECTED_EVT,fxMarketWatchPriceService){
$scope.symbolSelected = function(currency){
$scope.$emit(SYMBOL_SELECTED_EVT,currency);
}
$scope.bullBear = function(newPrice){
if ($scope.oldPrice> newPrice ){
return ['glyphicon glyphicon-arrow-down','priceDown'];
}
else if ($scope.oldPrice > newPrice ){
return ['glyphicon glyphicon-arrow-up','priceUp'];
}
}
$scope.$on('socket:fxPriceUpdate', function(event, data) {
$scope.rates = data.payload;
});
}
}
})
You could modify the ng-class and move the logic into the view, because styling and placing classes shouldn't be done in code.
<div class="col-1-4">
<span class="glyphicon" ng-class="{'glyphicon-arrow-up priceUp': oldPrice > rate.bidPoint, 'glyphicon-arrow-down priceDown':oldPrice > rate.bidPoint}"></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
Or like this:
<span class="glyphicon {{oldPrice > rate.bidPoint ? 'glyphicon-arrow-down priceDown':'glyphicon-arrow-up priceUp'}}></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
I will recommend you to use both ng-class and $watcher. The two can actually compliment each other:
UPDATE: To make the code works with ng-repeat, we need to migrate all of CSS classes logic to another controller:
app.controller('PriceController', function($scope) {
// we first start off as neither up or down
$scope.cssBid = 'glyphicon';
$scope.cssOffer = 'glyphicon';
var cssSetter = function(newVal, oldVal, varName) {
if (angular.isDefined(oldVal) && angular.isDefined(newVal)) {
if (oldVal > newVal) {
$scope[varName] = 'glyphicon glyphicon-arrow-down priceDown';
} else if (newVal > oldVal) {
$scope[varName] = 'glyphicon glyphicon-arrow-up priceUp';
} else {
$scope[varName] = 'glyphicon';
}
}
};
// watch for change in 'rate.bidPoint'
$scope.$watch('rate.bidPoint', function(newVal, oldVal) {
cssSetter(newVal, oldVal, 'cssBid');
});
// watch for change in 'rate.offerPoint'
$scope.$watch('rate.offerPoint', function(newVal, oldVal) {
cssSetter(newVal, oldVal, 'cssOffer');
});
});
Next, we bind this PriceController onto ng-repeat div. By doing so, Angular will create one controller instance for each rate in rates. So this time rate.bidPoint and rate.offerPoint should be available for $watch-ing:
<div ng-repeat="rate in rates" ng-click="symbolSelected(rate)" ng-controller="PriceController">
<div class="col-1-4">
<span ng-class='cssBid'></span> {{rate.bidBig}}<span class="point">{{rate.bidPoint}}</span>
</div>
<div class="col-1-4">
<span ng-class='cssOffer'></span> {{rate.offerBig}}<span class="point">{{rate.offerPoint}}</span>
</div>
</div>
Now, directive's controller will be much shorter than before:
controller: function($scope, SYMBOL_SELECTED_EVT, fxMarketWatchPriceService){
$scope.symbolSelected = function(currency) {
$scope.$emit(SYMBOL_SELECTED_EVT, currency);
}
$scope.$on('socket:fxPriceUpdate', function(event, data) {
$scope.rates = data.payload;
});
}

Angular Radio Values in ng-repeat

I'm new to Angular and am trying to capture the selected radio value but the documentation is not clear when using ng-repeat. Any help would be greatly appreciated.
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-change="getPlanTypes()" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}">
{{item['date']}} </label>
</div>
Here is the controller but I'm unsure of the right way to get the selected radio value?
rates.controller('getEffectiveDates',
function($scope, $http, $location, myService, localStorageService) {
myService.effective_dates().then(function(ed) {
$scope.ed = ed;
});
$scope.getPlanTypes = function() {
console.log($scope.ed['code']); //Futile attempt that returns undefined
localStorageService.add('code',$scope.ed['code']);
$location.path("/plan-types");
}
});
Do
ng-click="getPlanTypes(item.code)"
and in your controller, you can get the value
$scope.getPlanTypes = function (ed) {
console.log(ed);
}
http://jsfiddle.net/2LZpv/
The HTML
<div ng-app="myApp" ng-controller="getEffectiveDates">
<div ng-repeat="item in ed">
<label for="{{item['code']}}">
<input ng-click="getPlanTypes(item)" ng-model="ed" type="radio" id="{{item['code']}}" name="effective_date" value="{{item['code']}}"/>
{{item['date']}} </label>
</div>
</div>
The JS
angular.module("myApp",[]).controller('getEffectiveDates', ["$scope", function($scope) {
$scope.ed = [{code:'1',date:"test date 1"},{code:'2',date:"test date 2"}];
$scope.getPlanTypes = function(selectedItem) {
console.log(selectedItem["code"]); //Feeble attempt that returns undefined
}
}]);

Categories

Resources