Angular service with different angular app - javascript

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/

Related

Angular service function isn't working on user input

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>

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)
};

AngularJS - To Do App Place Submit and Delete Function into Factories

I've created a simple To Do App and while working on it I felt like I will end up placing too much code into my Controller and will eventually get messy and hard to read. I want to know how can I move my functions into factories so that my code can look somewhat cleaner.
Here is my JS:
angular.module('toDoApp', [])
.controller('toDoCtrl', function($scope){
//set $scope variables
$scope.tasks = [];
$scope.submitTask = function(){
$scope.tasks.unshift($scope.enteredTask);
$scope.enteredTask = '';
};
$scope.removeTask = function(task) {
var i = $scope.tasks.indexOf(task);
$scope.tasks.splice(i, 1);
};
})
.factory('toDoFactory', ['$http', function($http){
return function(newTask) {
};
}])
Here is the HTML if needed:
<form ng-submit="submitTask()">
<!-- task input with submit button -->
<label>Task: </label>
<input type="text" placeholder="Enter Task" ng-model="enteredTask" required>
<button>Submit</button>
</form>
<div>
<!-- create unordered list for task that are submitted
need check boxes -->
<ul>
<li ng-repeat="task in tasks">
{{ task }}
<button ng-click="removeTask()">x</button>
</li>
</ul>
</div>
As you can see I kinda started the factory but just don't know how to go about it.
Any suggestions will be greatly appreciated.
You will need to inject your factory inside controller and then use the methods defined in the factory from the controller:
angular.module('toDoApp', [])
.controller('toDoCtrl', function($scope, toDoFactory){
//set $scope variables
$scope.tasks = [];
$scope.submitTask = function(){
toDofactory.submittask(); //Just for demo.Passin your parameters based on your implementation
};
$scope.removeTask = function(task) {
var i = $scope.tasks.indexOf(task);
$scope.tasks.splice(i, 1);
};
})
.factory('toDoFactory', ['$http', function($http){
var methods = {};
methods.submittask = function(){
//your logic here
};
methods.removetask = function(){
//your logic here
}
return methods;
}])
var app = angular.module('toDoApp', []);
app.controller('toDoCtrl', function($scope, toDoFactory){
$scope.tasks = [];
toDoFactory.get = function(){
}
toDoFactory.delete = function(){
}
toDoFactory.update = function(){
}
});
app.factory('toDoFactory', ['$http', function($http){
var todo = {};
todo.get = function(){
};
todo.delete = function(){
};
todo.update = function(){
}
return todo;
}]);
This is simple architecture, you can add more logic,
Make sure you know about dependency injection(DI)
Here is the answer for those that want to see what the end result will look like when all the code is plugged in. Thanks again for the answers as it was able to guide me in the right direction.
.controller('toDoCtrl', function($scope, toDoFactory){
$scope.tasks = toDoFactory.tasks;
$scope.submitTask = function(){
toDoFactory.submitTask($scope.enteredTask);
$scope.enteredTask = '';
};
$scope.removeTask = function(task) {
toDoFactory.removeTask();
};
})
.factory('toDoFactory', ['$http', function($http){
var toDo = {
tasks: [],
enteredTask: '',
submitTask: function(task){
toDo.tasks.unshift(task);
},
removeTask: function(task) {
var i = toDo.tasks.indexOf(task);
toDo.tasks.splice(i, 1);
}
};
}])

My ng-model is not updating first time

i am having a problem with ng-model .When i am adding tag from suggestion list its not updating model value until i am not deleting tags and adding again.In my project its working fine but for plunker only its happening.Please check this out and help me..
thank you..
Here is my html:-
<tags-input ng-model="tags2" display-property="tagName" on-tag-added="getTags()" id="target">
<auto-complete source="loadTags($query)" min-length="2"></auto-complete>
</tags-input>
<p>{{tags2}}</p>
Here is my js:-
var app = angular.module('myApp', ['ngTagsInput', 'ui.bootstrap']);
app.controller(
'myController',
function($scope, $http) {
$scope.tagsValues =[];
$scope.loadTags = function(query) {
return $http.get('tags.json');
};
$scope.getTags = function() {
$scope.tagsValues = $scope.tags2.map(function(tag) {
return tag.tagId;
});
alert(" Tag id is :"+ $scope.tagsValues);
};
});
Here is my plunker:-
http://plnkr.co/edit/6Mr2qk2S2RvGJLevf2UI?p=preview
All you have to do to make this work, is define and initialize the variable $scope.tags2 first:
var app = angular.module('myApp', ['ngTagsInput', 'ui.bootstrap']);
app.controller(
'myController',
function($scope, $http) {
$scope.tagsValues = '';
$scope.tags2 = [];
$scope.loadTags = function(query) {
return $http.get('tags.json');
};
$scope.getTags = function() {
$scope.tagsValues = $scope.tags2.map(function(tag) {
return tag.tagId;
});
alert(" Tag id is :"+ $scope.tagsValues);
};
});
See my plunker: http://plnkr.co/edit/Y3f8kLBnexOXg5gwmldL?p=preview

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]);
}

Categories

Resources