Angular service function isn't working on user input - javascript

I'm trying to learn how to make angular services, so I' ve made one but it only works as the page loads and it gives input value instead of function result.
HTML:
<input type="text" ng-model="hexVal">
<p>Hex service: {{hex(hexVal)}}</p>
JS:
Service itself:
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
};
});
Usage of service:
$scope.hexVal = 255;
$scope.hex = function(arg){
return hexafy.myFunc(arg);
};

The input text needs to be parsed into a number:
app.service('hexafy', function() {
this.myFunc = function (x) {
return parseInt(x).toString(16);
};
});
The DEMO
angular.module("app",[])
.service('hexafy', function() {
this.myFunc = function (x) {
return parseInt(x).toString(16);
};
})
.controller('ctrl', function($scope,hexafy) {
$scope.hexVal = 255;
$scope.hex = function(arg){
return hexafy.myFunc(arg);
};
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<input type="text" ng-model="hexVal">
<p>Hex service: {{hex(hexVal)}}</p>
</body>

Related

Angular - Service to calculate sum of 2 scopes

Learning how to use services but really having a hard time. Trying to make a simple calculator to provide the sum of 2 scope value (2 inputs). My functions seems to be taking the values and sending them okay. But my result scope dosent seem to be changing or updating at all when I fire my functions.
Here what I got so far:
Jsfiddle:
https://jsfiddle.net/9bz4Lwxa/528/
HTML:
<body ng-app="myApp" ng-controller="myController">
Val1: <input ng-model="val1"> {{val1}} <br>
Val2: <input ng-model="val2"> {{val2}} <br><br>
Total result: <input ng-model="result"> {{result}} <br>
<input type="button" ng-click="calculate_controller()" value="Calculate"><br>
</body>
SCRIPT:
angular.module('myApp', [])
.controller('myController', function($scope, businessRepository) {
$scope.result = businessRepository.result_service();
$scope.val1 = "";
$scope.val2 = "";
$scope.calculate_controller = function() {
console.log("Hello");
businessRepository.calculate_service($scope.val1, $scope.val2)
};
})
.factory('businessRepository', function($http) {
return {
result_service: function(data){
console.log("test function launched", data)
return data;
},
calculate_service: function(val1, val2){
var result = val1 + val2;
this.result_service(result);
}
};
});
You need to return data from the service businessRepository and need to consume it in the controller myController. Also you need to convert val1 and val2 to Number. Here in snippet I have used + to achieve it.
angular.module('myApp', [])
.controller('myController', function ($scope, businessRepository) {
$scope.calculate_controller = function () {
$scope.result = businessRepository.calculate_service(+$scope.val1, +$scope.val2)
};
})
.factory('businessRepository', function ($http) {
return {
result_service: function (data) {
return data || 0;
},
calculate_service: function (val1, val2) {
var result = val1 + val2;
//Return the data from
return this.result_service(result);
}
};
});
angular.module('myApp', [])
.controller('myController', function($scope, businessRepository) {
$scope.calculate_controller = function() {
$scope.result = businessRepository.calculate_service(+$scope.val1, +$scope.val2)
};
})
.factory('businessRepository', function($http) {
return {
result_service: function(data) {
return data;
},
calculate_service: function(val1, val2) {
var result = val1 + val2;
return this.result_service(result);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
Val1:
<input ng-model="val1">
<br>Val2:
<input ng-model="val2">
<br>
<br>Total result:
<input ng-model="result">{{result}}
<br>
<input type="button" ng-click="calculate_controller()" value="Calculate">
<br>
</div>
You need to change the calculate_service by :
calculate_service: function (val1, val2) {
var result = parseInt(val1) + parseInt(val2);
return this.result_service(result);
}
And calculate_controller by :
$scope.calculate_controller = function () {
$scope.result = businessRepository.calculate_service($scope.val1, $scope.val2)
};

Angular service with different angular app

Here i am using angular service.In my case i am getting value for first app but not for second .please help me .
thank you.
here is my html:-
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="multiply()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>
<div ng-app="myApp2" ng-controller="myController2">
<p>Enter a number: <input type="number" ng-model="numberSecond" />
<button ng-click="multiplyValue()">X<sup>2</sup></button>
<p>Result: {{result2}}</p>
</div>
here is js:-
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function()
{
// code here
var factory = {};
factory.multiply = function(a)
{
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ['myReuseableMod']);
mainApp.controller('CalcController',['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
alert("inside controller");
$scope.multiply = function()
{
alert("hello1");
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
}]);
var mainApp2 = angular.module("myApp2", ['myReuseableMod']);
mainApp.controller('myController2',['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
alert("inside controller");
$scope.multiplyValue = function()
{
alert("hello1");
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
}
}]);
Your 'myController2' is in the wrong app
mainApp.controller('myController2'
Should be:
mainApp2.controller('myController2'
EDIT:
Ah yes I see the problem. You cannot use ng-app twice like that. If you want what you are trying to achieve which is multiple applications you have to 'bootstrap' the second one:
plunk here:
http://plnkr.co/edit/qfllLO9uy6bC5OLkHnYZ?p=preview
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function() {
var factory = {};
factory.multiply = function(a) {
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ["myReuseableMod"]);
mainApp.controller('CalcController', ['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
$scope.multiply = function() {
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
}]);
var mainApp2 = angular.module("mainApp2", []);
mainApp2.controller("MyController2", function($scope, $myReuseableSrvc) {
console.log('init B');
$scope.multiplyValue = function() {
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
}
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("myDiv2"), ["mainApp2", "myReuseableMod"]);
});
This is a good post to read:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/

Why Can't I change value of the variable? Angular

I made a service that stores a variable I use in two controllers.
function CommonVariables() {
var number = 3;
return {
setNumber: function(num) {
number = num;
},
getNumber: function() {
return number;
}
}
};
The problem is that I can get this variable like this:
this.number = CommonVariables.getNumber();
I want it to be changed like this:
<input class="numInput" ng-model="Ctrl.number">
in Js:
function Controller(CommonVariables) {
this.number = CommonVariables.getNumber();
CommonVariables.setNumber(this.number);
}
But I can't and don't understand why
You need to not only update the variable in the controller, but also send that update back to the service, from which it can be shared to any other part of your application.
=====================================================
edit: working code for me - check your console logs as you run it:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
<body>
<div ng-app="myApp" ng-controller="Ctrl">
<input class="numInput" ng-model="number" ng-change="changeNumber()">
</div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("Ctrl", function(CommonVariables, $scope){
//this will initially set it as the same number as is stored in CommonVariables
$scope.number = CommonVariables.getNumber();
//this is the function that will actually send that number back to the service to update it there
$scope.changeNumber = function() {
console.log("Number set:", $scope.number);
CommonVariables.setNumber($scope.number)
console.log("Number retrieved after setting:", CommonVariables.getNumber());
}
})
.factory("CommonVariables", function(){
var number = 3;
return {
setNumber: function(num) {
number = num;
},
getNumber: function() {
return number;
}
}
})
</script>
You need to $watch the property number in the controller scope.
Inject $scope and use
function Controller(CommonVariables, $scope) {
$scope.$watch(angular.bind(this, function () {
return this.number;
}), function (newVal) {
CommonVariables.setNumber(newVal);
});
...
By looking at your code assuming you are using controller as syntax

Controller hiding $scope.var in another controller with angular

I have 2 controllers. I want to make a simple toggle where if a function is called it hides code in the other controller. Here is what I have...
Angular:
var app = angular.module('plunker', []);
app.factory('data', function () {
var fac = [];
fac.hideIt = function (hide) {
console.log(hide)
if (hide != null)
return true;
else
return false;
};
return fac;
});
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
console.log(data.hideIt()); //its false
$scope.hide = data.hideIt();
});
app.controller('SecCtrl', function($scope, data) {
$scope.hideAbove = function () {
var hide = true;
data.hideIt(hide);
console.log(data.hideIt(hide)) //now it is true
}
});
HTML:
<div ng-controller="MainCtrl">
<div ng-if="hide == false">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE </div>
</div>
Link to Plunkr:
http://plnkr.co/edit/zOAf5vGMTAd8A10NGiS1?p=preview
Is there no way to use a controller to hide code that is in another controller?
You dont need to use $emit, $rootScope.$broadcast or something else
in your code you asked to the factory the value of a local variable, you cant updates it because each time you start the method a new variable was created;
Here is a working example, hope it will help you
http://plnkr.co/edit/jBc3DJnzXNJUiVVwRAPw?p=preview
The factory declare some useful methods like updates and gets hide value
app.factory('HideFactory', function () {
var prototype = {};
var hide = false;
prototype.getDisplayMode = function() {
return hide;
}
prototype.hideIt = function (val) {
hide = typeof val == 'boolean' ? val : false;
return val;
};
return prototype;
});
The controllers declare some variables which are a reference to the factory methods
app.controller('MainCtrl', ['$scope', 'HideFactory',function($scope, HideFactory) {
$scope.name = 'World';
$scope.isHide = HideFactory.getDisplayMode;
}]);
app.controller('SecCtrl', ['$scope', 'HideFactory', function($scope, HideFactory) {
$scope.isHide = HideFactory.getDisplayMode;
$scope.hideAbove = function() {
HideFactory.hideIt(true);
}
}]);
And the html, the ng-if directive call the isHide method, linked to the getDisplayMode method of the factory
<body>
<div ng-controller="MainCtrl">
<div ng-if="!isHide()">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE </div>
</div>
</body>
You're about halfway there with your factory, you have most of a setter but not a getter. Here's what I'd change.
Factory:
app.factory('data', function () {
var fac = [];
var state = false;
fac.hideIt = function (hide) {
state = hide;
};
fac.hidden = function() {
return state;
}
return fac;
});
Controller:
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
$scope.hide = data.hidden;
});
HTML:
<div ng-controller="MainCtrl">
<div ng-hide="hide()">
<p>Hello {{name}}!</p>
</div>
</div>
Forked Plunker
please see here: http://plnkr.co/edit/3NEErc0zUpXlb1LarXar?p=preview
var app = angular.module('plunker', []);
app.factory('data', function() {
var fac = [];
var _hide = {};
hideIt = function(hide) {
console.log("from fact " + hide)
if (hide !== null) {
_hide.state = true;
return _hide;
} else
_hide.state = false;
return _hide;
};
return {
fac: fac,
hideIt: hideIt,
hide: _hide
};
});
app.controller('MainCtrl', function($scope, data) {
$scope.name = 'World';
//console.log(data.hideIt()); //its false
$scope.hide = data.hide;
});
app.controller('SecCtrl', function($scope, data) {
$scope.hideAbove = function() {
var hide = true;
data.hideIt(hide);
}
});
HTML:
<div ng-if="hide.state != true">
<p>Hello {{name}}!</p>
</div>
</div>
<div ng-controller="SecCtrl">
<div ng-click="hideAbove()">CLICK HERE</div>
</div>
</body>
You want to use $emit.
function firstCtrl($scope){
$scope.$on('someEvent', function(event, data) { console.log(data); });
}
function secondCtrl($scope){
$scope.$emit('someEvent', [1,2,3]);
}

alternative method instead $watch in angularjs

I have a scope variable, when it returns true, i need to trigger some events or do something. I my case, the every first time, the scope variable returns undefined and later it returns true. In this case i used $watch method to get the expected funcionality. Is there any alternative approach to do the same instead using $watch ?
scope.$watch () ->
scope.initiateChild
, (value) ->
if value is true
$timeout ->
scope.buildOnboarding()
, 1000
You can try using AngularJS $on(), $emit() and $broadcast().
Here is an example: http://www.binaryintellect.net/articles/5d8be0b6-e294-457e-82b0-ba7cc10cae0e.aspx
You can use JavaScript getters and setters without any expense of using $watch.
Write code in the setter to do what you want when angular changes the your model's value you are using in scope. It gets null or an a State object as user types. Useful for working with type ahead text boxes that have dependencies on each other. Like list of counties after typing state without user selecting anything.
Here is some pseudo style code to get the idea.
<input ng-model="searchStuff.stateSearchText" />
<div>{{searchStuff.stateObject.counties.length}}</div>
<div>{{searchStuff.stateObject.population}}</div>
$scope.searchStuff=new function(){var me=this;};
$scope.searchStuff.stateObject = null;
$scope.searchStuff.getStateObjectFromSearchText = function(search){
// get set object from search then
return stateObject;
};
$scope.searchStuff._stateSearchText= "";
Object.defineProperty($scope.searchStuff, 'stateSearchText', {
get: function () {
return me._stateSearchText;
},
set: function (value) {
me,_stateSearchText = value;
me.stateObject = getStateObjectFromSearchText (value);
}
});
See this fiddle: http://jsfiddle.net/simpulton/XqDxG/
Also watch the following video: Communicating Between Controllers
A sample example is given below
Html:
<div ng-controller="ControllerZero">
<input ng-model="message" >
<button ng-click="handleClick(message);">LOG</button>
</div>
<div ng-controller="ControllerOne">
<input ng-model="message" >
</div>
<div ng-controller="ControllerTwo">
<input ng-model="message" >
</div>
javascript:
var myModule = angular.module('myModule', []);
myModule.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function(msg) {
this.message = msg;
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}
function ControllerOne($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'ONE: ' + sharedService.message;
});
}
function ControllerTwo($scope, sharedService) {
$scope.$on('handleBroadcast', function() {
$scope.message = 'TWO: ' + sharedService.message;
});
}
ControllerZero.$inject = ['$scope', 'mySharedService'];
ControllerOne.$inject = ['$scope', 'mySharedService'];
ControllerTwo.$inject = ['$scope', 'mySharedService'];

Categories

Resources