AngularJS : how to use ng-change in factories? - javascript

My html:
<div ng-controller="MainController">
<input type="text" ng-model="value" ng-change="change(value)">
</div>
My controller:
app.controller('MainController', ['$scope', function($scope){
var search;
$scope.change = function(value) {
search = value;
}
}]);
It works great.
Now I want to use this function (ng-change) into factory, but I don't know how. So, my controller:
app.controller('MainController', ['$scope', 'MainFactory', function($scope, MainFactory){
$scope.search = MainFactory.getSearch();
}]);
My factory:
app.factory('MainFactory', function(){
var search;
return {
getSearch: function() {
whatMustBeHere.change = function(value) {
search = value;
}
return search;
}
}
});
Maybe, there is some other way to solve this issue? Thanks a lot.

Use getters and setters to save the value in your factory
You can just set the value onChange (Don't forget to inject the factory in your controller)
Like this:
app.controller('MainController', ['$scope', function($scope, MainFactory){
$scope.search = MainFactory.getSearchValue();
$scope.change = function(value) {
MainFactory.setSearchValue(value);
}
}]);
and in your factory
app.factory('MainFactory', function(){
var search;
return {
setSearchValue: function(value) {
this.search = value;
}
getSearchValue: function() {
return this.search;
}
}
});

Related

Passing variables betweencontrollers in angular js

I am new to angular js and its services so please bear with this basic question. Please read comment inside code to understand what I need.
.controller('ctrlr1', function($scope, myservice) {
var a = "abc";
})
.controller('ctrl2', function ($scope, myservice) {
// how to get value of a
})
.service('myservice', function() {
//what goes here?
});
Thanks in advance
Basic sharing by angular services
.controller('ctrlr1', function($scope, myservice) {
var a = "abc";
var b = 123;
myservice.myData = a;
myservice.myDataB = b;
})
.controller('ctrl2', function ($scope, myservice) {
// how to get value of a
console.log(myservice.myData);
console.log(myservice.myDataB);
})
.service('myservice', function() {
//what goes here?
this.myData = '';
this.myDataB = 0;
});
You can use myservice because its the efficient way but don't use $brodcast.
Here is an example:-
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});

How can I disable $logProvider?

I am confused with $logProvider...
I have disabled the logs messages, but I am still getting the log.
Can any one help me what wrong in this code?
angular
.module("myModule", []).config(function ($logProvider) {
$logProvider.debugEnabled(false);
})
.controller("myController", ['$scope','$log', function ($scope, $log) {
$log.debug("This is sample text");
$log.warn("This is sample text");
$log.error("This is sample text");
$log.info("This is sample text");
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myModule" >
<div ng-controller="myController">
</div>
</body>
$logProvider.debugEnabled(false); only disable the debug level of $log, that is why you can still use $log.warn, $log.error and $log.info.
More about that here.
If you want to completely turn off $log, check this link and especially this part of the code:
$logProvider.debugEnabled(true);
$provide.decorator('$log', ['$delegate', function ($delegate) {
$delegate.table = angular.noop;
return $delegate;
}]);
$provide.decorator('$log', ['$delegate', function ($delegate) {
$delegate.info = angular.noop;
return $delegate;
}]);
$provide.decorator('$log', ['$delegate', function ($delegate) {
$delegate.warn = angular.noop;
return $delegate;
}]);
$provide.decorator('$log', ['$delegate', function ($delegate) {
$delegate.error = angular.noop;
return $delegate;
}]);
Hope this helps you...
angular.module("myModule", [])
.config(['$provide',
function($provide) {
$provide.decorator('$log', ['$delegate',
function($delegate) {
var origDebug = $delegate.debug;
$delegate.debug = function() {
var args = [].slice.call(arguments);
args[0] = [new Date().toString(), ': ', args[0]].join('');
origDebug.apply(null, args)
};
return $delegate;
}
]);
}
])
.controller("myController", ['$scope', '$log',
function($scope, $log) {
$log.debug("This is sample text");
$log.warn("This is sample text");
$log.error("This is sample text");
$log.info("This is sample text");
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div ng-app="myModule">
<div ng-controller="myController">
</div>
</div>

Angular Service using Factory, the data is correct but not showed at UI

So far this is the complete source
angular
.module('app')
.factory('Friends', ['$http',function($http){
return {
get: function(){
return $http.get('api/friends.json')
.then(function(response){
alert(JSON.stringify( response.data));
return response.data;
});
}
};
}])
Controller:
angular.module("app")
.controller('homeCtrl',['$scope','Friends',
function($scope, Friends){
$scope.title = "Welcome";
$scope.items=["2016","2015", "2014"];
$scope.friends = Friends.get();
$scope.save = function(){
$http.post('/api/friends', friends);
}
}])
$stateProvider
.state('home',{
url:'/',
templateUrl:'templates/home.html',
controller: 'homeCtrl',
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}
})
The result when I try to alert it:
The UI Blank:
*and my nav bar ddl is not working how to do the trick?
Friends.get() return a promise. You must use the then method :
Friends.get().then(function(data) { $scope.friends = data; }); //instead of $scope.friends = Friends.get();
you should use $q for promises:
angular
.module('app')
.factory('Friends', ['$http', '$q' ,function($http, $q){
var self = {};
self.get = function() {
var deferred = $q.defer();
$http.get('api/friends.json')
.success(deferred.resolve)
.error(deferred.reject)
return deferred.promise;
}
return self
}])
Resolve:
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}

AngularJS: $routeParams to work within a service

I know this is easy, but I can't quite wrap my head around how to do this.
I need to do the API call within a service so that those variables can be accessed between two separate controllers.
The problem I am having is I can't access $routeParams (which I need for the get) within the service. I can't figure out know how to pass $routeParams from the controller to the service.
app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
var posts = function posts() {
$http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
console.log(JSON.stringify(res) );
});
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts
};
}]);
factory :
app.factory('Page', ['$http', function($http) {
var _posts = function posts(param) {
return $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts : _posts
};
}]);
Controller :
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
Page.posts($routeParams.slug).then(function success(response) {
$scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);
please note that success is deprecated in newer versions of Angular. I have updated the code with then

calling method from one controller to another controller in angular js

I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here

Categories