function calling a service only works when initializing - angularjs

Getting started with AngularJS working through the W3schools tutorial.
I'm trying to expand on some of the sample code by creating an input which is used by the function getHex(), which uses the service hexafy.
<div ng-app="myApp" ng-controller="myCtrl">
<p>The hexadecimal value of <input ng-model="inputNo"/> is:</p>
<h1>{{getHex()}}</h1>
</div>
<p>A custom service with a method that converts a given number into a hexadecimal number.</p>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.inputNo = 255;
$scope.getHex = function() {
return hexafy.myFunc($scope.inputNo);
};
});
</script>
When the page firsts load, the input contains 255 and the {{getHex()}} is rendered as ff, so the function appears to run correctly.
But when I change the value in the input, it just returns exactly my input into {{getHex()}} without hexify-ing it. getHex() is supposed to return the result of hexafy.myFunc.

convert the $scope.inputNo to int before sending to the service
return hexafy.myFunc(parseInt($scope.inputNo));
Demo

Convert the sent payload to a javascript Number before converting to hex.
var app = angular.module('myApp', []);
app.service('hexafy', function() {
var hexafyService = {};
var _myFunc = function(x) {
return Number(x).toString(16);
}
hexafyService.myFunc = _myFunc;
return hexafyService;
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.inputNo = 200;
$scope.getHex = function() {
$scope.hexNo = hexafy.myFunc($scope.inputNo);
};
$scope.getHex();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<p>The hexadecimal value of <input ng-model="inputNo" ng-change="getHex()" /> is:</p>
<h1>{{hexNo}}</h1>
</div>
<p>A custom service with a method that converts a given number into a hexadecimal number.</p>

Related

Angular Filter in AngularJs

var app = angular.module('pixmall', []);
app.controller('myDashboard', function($scope, $http) {
app.filter('myRandom', function() {
return function (input) {
return Math.round(input);
}
});
<div ng-app="pixmall" ng-controller="myDashboard">
<span>{{30.35 | myRandom}}</span>
</div>
I want to use the filter to round the number to the nearest whole number but it is not working, I don't know what is wrong
Separate out the controller and filter, you should not place the filter within the controller code.
DEMO
var app = angular.module('pixmall', [])
app.controller("myDashboard",function($scope){
});
app.filter('myRandom', function() {
return function (input) {
return Math.round(input);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.7/angular.min.js"></script>
<div ng-app="pixmall" ng-controller="myDashboard">
<span>{{30.35 | myRandom}}</span>
</div>

How to use angular.bind(self, fn, args)

I am new to angular js. I was gone through the angular api references,
I had seen function called angular.bind(self, fn, args).
I could not understand the usage of this function. Can anyone explain this function with one example?
It used in Function Currying. An example with JavaScript:
var concat = function(input1) {
return function(input2) {
console.log(input1 + ", " + input2);
};
};
var externalFunction = concat("Hello");
externalFunction("World!"); // gives: "Hello, World!"
This allows you to use only some parameters and not all, for example concant("Hello") instead of concant("Hello","World!"). You can imagine using a defined variable as one of the parameters, whereas you fill in the second one from a user input. The same concept can be used with AnuglarJS:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
</head>
<body ng-app="app">
<div ng-controller="bindController">
<input type="number" ng-model="num" ng-change="AddValue()" />
Adding 5: {{Add}}
</div>
</body>
</html>
<script>
var app = angular.module("app", []);
app.controller('bindController',['$scope',function($scope){
$scope.num = 30;
$scope.AddValue = function () {
var addData = angular.bind(this, function (a, b) {return a + b;});
$scope.Add = addData(5, $scope.num);
}
$scope.AddValue();
}]);
</script>
Controller
app.controller('Identity`enter code here`Controller', ['$scope',
function($scope) {
$scope.Name = "";
$scope.Result = "";
var greet = function (greeting, punctuation) {
$scope.Result = greeting + ' ' + $scope.Name +''+ punctuation;
};
$scope.callBind = function () {
var bound = angular.bind(this, greet, 'Welcome');
bound('!!!!!');
};
}]);
html
<fieldset style="background-color:#DDE4E9;">
<legend>AngulerJS $scope.bind() Example</legend>
<div ng-controller="IdentityController">
<p>{{Result}}</p>
<input ng-model="Name">
<button ng-click="callBind()">Call Bind</button>
</div>
</fieldset>
I Think Its Working

Substr in angularJS to fetch the initials of the full name

My question is related to creating substr in Angular.JS
Suppose i have a model:
$scope.myName = 'John Smith'
but when during the rendering of the model on the page i need only the initials of the name like:
<p>{{myName | some directive/filter }}<p>
Output should be :: JS
i tried creating many directives but unable to fetch the exact output even i have tried the limitTo filter but it give only the starting first 2 letters of the name.
Workbook is here
With assumption that name tokens are separated by SPACE , as given in your question
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<label>Name : {{name}}</label><br/>
<label>Short Name : {{name|shortName}}</label>
</div>
<script>
var app = angular.module('myApp', []);
app.filter('shortName', function() {
return function(x) {
var shortName="", nameTokens=[];
nameTokens = x.split(" ");
nameTokens.forEach(function(token){ shortName+=token[0] });
return shortName;
};
});
app.controller('namesCtrl', function($scope) {
$scope.name = 'John Smith';
});
</script>
</body>
angular
.module('myApp',[])
.run(function($rootScope){
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', function($scope){
$scope.myName = 'saurabh raman';
}]).filter('filter', function() {
return function(input) {
var name = input;
var inls = name.match(/\b\w/g) || [];
inls = ((inls.shift() || '') + (inls.pop() || '')).toUpperCase();
return inls;
}
});
view
<p>{{myName | filter}}</p>
</body>
</html>
I was hoping there was a built-in filter for it, but it seems there isn't one, so I've created this filter:
var relConclusaoApp = angular.module("relatorioConclusaoApp", []);
relConclusaoApp.filter('onlyinitials', [function () {
return function (input) {
if (input) {
return input
.split(/\s+/)
.filter(s => s.length > 2)
.map(s => s.charAt(0).toLocaleUpperCase())
.join(".")
.concat(".")
}
return input;
}
}])
This filter is going to transform Floor Jansen into F.J. (e.g.)
It should be used in your template as:
{{nameToBeTransformed | onlyinitials}}

AngularJS showing html scope as raw text

i'm using an API to get my posts of my blog. But i'm getting the content that's a HTML code but i'm trying to see it as i saw in the blog but aren't working.
I had tried it using this filter and functions:
.filter('unsafe', function($sce) {
return function(val) {
return $sce.trustAsHtml(val);
};
})
And in controller:
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
In the template:
<div ng-bind-html="post.conteudo | unsafe"></div>
But this codes aren't making this work properly. As result of this, i get a raw/plain text like this:
What can i do?
You are overcomplicating things. You don't need this filter, as well as htmlDecode function. All you need is $sce.trustAsHtml:
$scope.post.conteudo = $sce.trustAsHtml('<b>Thomas Mann</b>');
and in HTML:
<div ng-bind-html="post.conteudo"></div>
angular.module('demo', []).controller('DemoController', function($scope, $sce) {
$scope.post = {}
$scope.post.conteudo = $sce.trustAsHtml('<b>Thomas Mann</b>')
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo" ng-controller="DemoController">
<div ng-bind-html="post.conteudo"></div>
</div>

Angularjs not updating variables

I want to display/update the calculation answer directly without the need of aditional buttons.
Or do i need a function and button to apply the changes?
<div ng-app="myApp" ng-controller="myCtrl">
A_Number: <input type="number" step="1" ng-model="A_Number"><br>
Display (A_Number): {{A_Number}}
<br>
square: {{square}}
</div>
controller:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.square = $scope.A_Number * $scope.A_Number;
});
</script>
Make square as a method & use that method in interpolation directive, so that will evaluate on each digest.
Markup
square: {{square()}}
Code
$scope.square = function(){
//made error free
if(!isNaN($scope.A_Number))
return $scope.A_Number * $scope.A_Number;
return 0;
};
Add watch on A_Number to achieve the same. JSFiddle for reference -
https://jsfiddle.net/9a2xz61y/3/
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.square = 0;
$scope.$watch('A_Number', function(newValue, oldValue) {
{
if (!isNaN(newValue)) {
$scope.square = $scope.A_Number * $scope.A_Number;
}
}
});
});

Resources