AngularJS show url or plain text if value contain text - angularjs

How can I show in AngularJS and url or a plain text if a variable contains text?
For example let's have the model
$scope.model = {
Url: ''
};
<div data-ng-controller="myController">
if (model.Url)
{
URL
}
else
{
<p>{{model.Url}}</p>
}
<div>
P.S. The if else condition is for demo purpose, so how can I acheieve that using a directive like data-ng-if ?

You can try something like this:
<div data-ng-controller="myController">
<a ng-if="model.Url" ng-href="{{model.Url}}">URL</a>
<p ng-if="!model.Url">{{model.Url}}</p>
<div>
Note: you should use ng-href instead of href otherwise browser doesn't update attribute.
Update
This thing works only if url present or empty as in provided example. It doesn't check is value url or text. See answer below that checks.

Create a function to test if a block of text is a URL or not
$scope.isURL = function(text){
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
// alternative
// var expression = new RegExp("^(http[s]?:\\/\\/(www\\.)?|ftp:\\/\\/(www\\.)?|www\\.){1}([0-9A-Za-z-\\.#:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
var regex = new RegExp(expression);
/// for example text could be: text = 'www.google.com';
if (text.match(regex) ){
return true;
} else {
return false;
}
}
HTML:
<div data-ng-controller="myController">
<div ng-init="model.url = 'some text'"></div>
<div ng-if="isURL(model.url)">
<a ng-href='model.url' > is url </a>
</div>
<div ng-if="!isURL(model.url)">
<p ng-bind='model.url' > </p>
</div>
<!-- better done as ng-switch -->
<div ng-switch on="isURL(model.url)">
<p ng-switch-when='false' ng-bind='model.url'></p>
<a ng-switch-when='true' ng-href='model.url' ng-bind='model.url'></a>
</div>
<div>

Related

Get checked values in other view

I have list of checkbox with button submit , and I when i click on submit, I have to get all checked values in other view table. I find a lot of answers, but they all propose to get values in the same view,but I need to get values in other view(ajoutFactAdmin2), how can I do that please. this is the code:
ajoutFactAdmin2.html
<div class="row" ng-repeat="x in namesF3">
<div class="col"><input type="checkbox" name="" ng-modal="x.selected" ng-checked="exist(x)" ng-click="toggleSelection(x)" ng-true-value="'{{x.CodeEnvoiColis}}'" ng-false-value="''" id="'{{x.CodeEnvoiColis}}'"></div>
<div class="col" >{{x.CodeEnvoiColis}}</div>
<div class="col" width="20%">{{x.StatutColis}} </div>
<div class="col" width="20%">{{x.VilleDestColis}}</div>
</div>
<div class="selectedcontent">
<h3> Selected Names </h3>
<p ng-repeat = "selectedName in selected"> {{selectedName.CodeEnvoiColis}} </p>
</div>
<a class="button button-info" ng-click="toggleSelection(x)" href="#/ajoutFactAdmin2" style="background-color:#1627C0;float: right;">Ajouter</a>
app.js :
$scope.selected = [];
$scope.namesF3 = [];
$scope.exist = function(item){
return $scope.selected.indexOf(item) > -1;
}
$scope.toggleSelection = function(item){
var x = [];
var idx = $scope.selected.indexOf(item);
if(idx > -1){
$scope.selected.splice(idx, 1);
}
else{
$scope.selected.push(item);
}
}
You have to do like when user click submit button you need to call one function on controller and stored all value checked value in local storage and redirect to next page and next controller you have to get local storage value and display in view page.
or
You can do like from controller function you have to pass array as string and in next controller get state param value and use json.parse for convert string to object and display in html

Test if an object is an empty object in a AngularJS template

I have a simple object in a controller which can sometimes be empty ({}).
app.controller('TestController', function() {
var vm = this;
vm.testObject = {};
});
I want to hide or show some DOM-elements in the corresponding template when the object is empty or not.
I tried to do it with a simple <div ng-if="vm.testObject"> but when vm.testObject === {} it is considered true in the ng-if.
<div ng-controller="TestController as vm">
<div ng-if="vm.testObject">
Test Object is not empty
</div>
<div ng-if="!vm.testObject">
Test Object is empty
</div>
</div>
Is there a simple way to check for an empty object in the template? Preferably without adding new variables to the scope.
Here is a working Plunker:
http://plnkr.co/edit/Qed2MKmuedcktGGqUNi0?p=preview
You should use an AngularJs filter:
Javascript:
app.filter('isEmpty', [function() {
return function(object) {
return angular.equals({}, object);
}
}])
Html template:
<div ng-if="!(vm.testObject | isEmpty)">
Test Object is not empty
</div>
<div ng-if="vm.testObject | isEmpty">
Test Object is empty
</div>
Updated plunkr: http://plnkr.co/edit/J6H8VzUKnsNv1vSsRLfB?p=preview
Are you ok with moving the equality check to the ng-if?
<div ng-controller="TestController as vm">
<div ng-if="!equals({}, vm.testObject)">
Test Object is not empty
</div>
<div ng-if="equals({}, vm.testObject)">
Test Object is empty
</div>
</div>
Otherwise, provide a helper on the scope
app.controller('TestController', function() {
var vm = this;
vm.testObject = {};
vm.empty = function() {
return vm.testObject === {};
};
});
then
<div ng-controller="TestController as vm">
<div ng-if="!vm.empty()">
Test Object is not empty
</div>
<div ng-if="vm.empty()">
Test Object is empty
</div>
</div>
This is an old thread but I find easier to check if the Object has keys.
<div ng-controller="TestController as vm">
<div ng-if="Object.keys(vm.testObject).length">
Test Object is not empty
</div>
<div ng-if="!Object.keys(vm.testObject).length">
Test Object is empty
</div>
</div>
It's simple and readable.
This will work. check the Length
<div ng-if="!!vm.testObject && vm.testObject.length > 0">
Test Object is not empty
</div>
You can convert the object to a JSON string using the built-in AngularJS json filter and do a comparison like this:
<div ng-if="vm.testObject | json) != '{}'">
Test Object is not empty
</div>

pass Angular variables to Laravel

I load data via Angular ajax. How can I pass returned results to laravel #include partial?
Angular:
$scope.findItem = function(itemId) {
$scope.spinner = true;
$http.get('item/' + itemId).success(function(results) {
$scope.spinner = false;
$scope.results = results[0];
});
};
html:
<div ng-init="findItem(185)">
<span ng-show="spinner" class="spinner"></span>
<div ng-hide="results == undefined">
#include('partials.item', {{ results }}) // <- I want to pass 'results' here
</div>
</div>
You can't really do that. But you can just include the results variable as javascript in your partials.item view. So your HTML would look like this:
<div ng-init="findItem(185)">
<span ng-show="spinner" class="spinner"></span>
<div ng-hide="results == undefined">
#include('partials.item')
</div>
</div>
And your partials.item view would have angular variables instead of laravel variables:
#{{results}}
Instead of
{{$results}}
Make sense?

AngularJs how to reload a template page after selecting a charater

I am using http.get and i need to reload a template after selecting a character so that my template gives the answer according to what I selected
The code of the template
<div class="container-fluid" ng-controller="CriterioCtrl">
<div id="result"></div>
<div>
Selected Items:
<div ng-repeat="id in selection">
{{id}}
</div>
</div>
<div ng-repeat-start="crit in data" class="row">
<h2 align="center">{{crit.name}}</h2>
<div ng-repeat="caracter in crit.characters" class="col-md-4">
<div type="checkbox" value="{{caracter.id}}" ng-checked="selection.indexOf(caracter.id) > -1" ng-click="clickSelection(caracter.id)">
<a href="#crit" class="thumbnail" ng-click="clickCriterios(caracter.id)">
<h4 align="center">{{caracter.name}}</h4>
<img ng-src="http://skaphandrus.com/{{caracter.image_url}}"/>
</a>
</div>
</div>
</div>
<div ng-repeat-end>
</div>
<!--<button class="btn" ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p> codigo de um botao -->
</div>
This code is for the selection
$scope.selection=[];
$scope.clickSelection = function clickSelection(caracterId) {
var idx = $scope.selection.indexOf(caracterId);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(caracterId);
}
var selectedId = $scope.selection;
console.log(selectedId);
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("idSelect", selectedId);
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("idSelect");
}
};
This code is the http part in another controller
MyApp.controller('EspeciesCtrl', function ($scope, $http) {
$http({
url: 'someurl',
method: "post",
params: {module_id: localStorage.getItem("idMod"),"characters[]": [localStorage.getItem("idSelect")]}
})
.then(function(res){
$scope.data = res.data;
});
});
This is the code of the template that have to change after the selection
<div class="container-fluid" ng-controller="EspeciesCtrl">
<div class="row">
<div ng-repeat="esp in data" class="col-md-6">
<a href="#infEsp" class="thumbnail" ng-click="clickEspecie(esp.id)">
<h4 align="center">{{esp.name}}</h4>
<img ng-src="{{esp.image_src}}"/>
</a>
</div>
</div>
</div>
How can i do that?
edit 1
If I've correctly understood, you may need to use ng-show (https://docs.angularjs.org/api/ng/directive/ngShow) whose boolean value checks if the user selected anything and show the extra bit of code you need, instead of trying to have another http request.
Also, it seems like you are using $scope.data for both the esp and the crit, so you will end up with the errors.
You probably don't need to reload the template.
You may want to use the data in $scope.data inside the template in order to let Angular manage the update on the view. As soon as the $scope.data changes, the rendered HTML changes too.
I can't comment but it would be helpful if you could share the template you are using and be more specific in your request :)

AngularJS display only div when string contains

How to in AngularJS display only div when in json filename contain for example jpg string?
I have got a list with file in json with .jpg pdf and other stuffs. I display theme by using ng-repeat and filter{filename:'jpg'}. It's works fine. But how to hide the div when jpg does not exist ?
<div>
<div>JPG FILES</div>
<ul ng-repeat="">
<li>name<a href='#'>download</a></li>
</ul>
</div>
I'm still not sure what you want, but this will hide the outer div if filtered results is empty.
<div ng-hide="filteredResults.length === 0">
<div>JPG FILES</div>
<ul ng-repeat="attachment in filteredResults = (example.attachments | filter: {file_name:'jpg'})">
<li>{{attachment.file_name}}<a href='#'>download</a></li>
</ul>
</div>
Hope this helps.
something like this ?
ng-show="filename == 'jpg'"
filename have to be in your scope
in yout controller
$scope.filename = "jpg";
HTML:
<div>
<div ng-if="hasImage">JPG FILES</div>
<ul ng-repeat="">
<li>name<a href='#'>download</a></li>
</ul>
</div>
JS:
$scope.hasImage = function()
{
if(yourjsonfile.indexOf("jpg") > -1)
{
return true;
}else
{
return false;
}
}

Resources