I'm trying to pass data from one controller to another using a factory and for some reason my factory isn't getting recognized in angular seed. Here is my app.js file which I'm declaring my factory
var myApp = angular.module('myApp', ['myApp.controllers','angularFileUpload', 'ngRoute']);
//
//
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/' ,{templateUrl:"/syncproto/partials/videoSlides.html"}, "sync").
when('/scenarios', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl").
when('/scenarios/:id', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl")
}]);
myApp.factory('Data', function() {
var Data;
return {
getData: function () {
return Data;
},
setData: function(value) {
Data = value;
}
};
});
Here is the controller which I'm using the factory Data
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data) {
$scope.scenarios = [];
$scope.thumbnails = [];
$scope.init = function(){
console.log('init hit');
$http({ method: 'GET', url: 'http://localhost:3000/scenarios' }).
success(function (data, status, headers, config) {
angular.forEach(data, function(scenario) {
if (scenario.video.length != 0 && scenario.video[0].thumbnailLocation != undefined){
$scope.thumbnails.push(scenario.video[0].thumbnailLocation);
//console.log('thumbnail is' + scenario.video.thumbnailLocation);
$scope.scenarios.push(scenario);
console.log(scenario.video[0].thumbnailLocation);
}
});
//console.log($scope.scenarios);
console.log('success');
}).
error(function (data, status, headers, config) {
console.log('error');
});
console.log($scope.thumbnails);
}
$scope.showVideo = function(scenario){
Data.setData(scenario);
$location.path('/');
//Data.setData($scope.scenarios[$scope.thumbnail.indexOf(thumbnail)]);
}
}])
The problem is that in $scope.showVideo = function(scenario) when i call Data.setData(scenario); I get the error TypeError: Object #<Object> has no method 'setData'
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data)
You're missing one argument for the $location service here. It should be
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, $location, Data)
Related
I am not able to assign the scope variable after a HTTP post request.
controller:
storeApp.controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.variableToBeAssigned= null;
}
$scope.formsubmit = function () {
$http.post($scope.url, { "name": $scope.name}).
success(function (data, status){
$scope.variableToBeAssigned= "success";
})}
The formsubmit() function is called when the user submits the form. The "variableToBeAssigned" remains null even after the HTTP Post request.
You should place the function inside the controller,
storeApp.controller("formCtrl", ['$scope', '$http', function ($scope, $http) {
$scope.variableToBeAssigned= null;
$scope.formsubmit = function () {
$http.post($scope.url, { "name": $scope.name}).
success(function (data, status){
$scope.variableToBeAssigned= "success";
return($scope.test1);
})}
}
I am new to Angular. I have created an app that, given the click of a button, should trigger a call that gets a set of json objects and populate a specific table. In the following controller code I have managed to populate the table directly without the click of a button (via the this.tableParams), but what I want is to trigger this data fetching process and populate the table only when the populateTable() function is called.How do I do it?
(function() {
'use strict';
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
//
}
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}]);
})();
Why not creating the NgTableParams-object inside the populateTable-function?
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}.bind(this);
}]);
Not the .bind(this). This ensures the this keyword means the same inside the populateTable-function as in the controller.
Move this.tableParams into the $scope.populateTable function. Bind this function to a button in the view e.g <button ng-click="populateTable()">Click Me!</button>
I am binding translation.
The issue is , some object convert to translated value, while some like mentioned below didn't work. This issue happened only first time when I build project. On refresh it gets fine.
This is not happening to all html objects.
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);
Html:
<b> {{('Heading' |translate)}}</b>
I got it.
The issue is with deferred,
It did not resolve properly and get return.
The Key line is:
deferred.promise.then(function () {});
Here is the fixed code:
angular.module('App').factory('APILoader', ['localStorageService', '$http', '$q', function (localStorageService, $http, $q) {
var translationAPIUrl = "Translation/Get";
return function (options) {
var deferred = $q.defer();
$http.get(translationAPIUrl, { params: { id: culture } }).success(function (response) {
data = JSON.parse(response.data);
deferred.resolve(data);
deferred.promise.then(function () {});
});
}).error(function (data) {
deferred.reject(options.key);
});
return deferred.promise;
};
}]);
I am learning Angular. The following code works:
.controller('abc', function ($scope, $http)
{
$http.get("/Handlers/Authentication.ashx")
.success(function (data)
{
alert(data);
})
This function however does not:
.controller('abc', function ($scope, $http)
{
$scope.run = function ($scope, $http)
{
$http.get('/Handlers/Authentication.ashx');
// .success(function (data)
//{
// alert(data);
//});
};
}
I know that I should use a service here. But for learning purposes I would like to know why it does not work to call this function inside:
<body ng-app="MainModule">
<div ng-controller="abc">
<div>
<button type="button" class="btn btn-info" ng-click="run();">{{xx}}</button>
Thank you for help in advance
You're overriding controller injected $http service here :
$scope.run = function ($scope, $http)
{
$http.get('/Handlers/Authentication.ashx');
// .success(function (data)
//{
// alert(data);
//});
};
Just remove all arguments on your scope function and it should work :
.controller('abc', function ($scope, $http) {
$scope.run = function () {
$http.get('/Handlers/Authentication.ashx')
.success(function (data){
alert(data);
});
};
}
Because you are getting data, but don't doing with it something.
$http.get('/Handlers/Authentication.ashx').then(function(data){
console.log(data);
}, function(err){
console.log(err);
})
I am writing an angularJs app:
html :
<div ng-controller=NavCtrl>
<h1 ng-bind-html="currentTitle"></h1>
</div>
I am searching for a way to update the currentTitle variable in my html which is in global scope.
.service('WorkService', [function(){
return {
currentTitle : 'dada'
};
}])
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
$scope.works = [];
$http({method: 'GET', url: '/api/v1/work'}). //collects all works
success(function(data, status, headers, config) {
$scope.currentTitle = WorkService.currentTitle;
})
})
.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {
$http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
success(function(data, status, headers, config) {
$scope.activateButton($routeParams.workId);
WorkService.currentTitle = data.title;
})
})
But currentTitle variable is not updated in the template. What am i doing wrong?
When you do WorkService.currentTitle = data.title current scope is unaware of this change. That is why you wont see the change in the template.
It is not ideal but for this requirement you may keep the currentTitle in $rootScope and keep update $scope.currentTitle in each controllers and that will do.
.run(function($rootScope){
$rootScope.globalData = {currentTitle : 'dada'}
})
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
$scope.works = [];
$http({method: 'GET', url: '/api/v1/work'}). //collects all works
success(function(data, status, headers, config) {
$scope.globalData.currentTitle = 'New title';
})
})
.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {
$http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
success(function(data, status, headers, config) {
$scope.activateButton($routeParams.workId);
$scope.globalData.currentTitle = data.title;
})
})
And in html
<h1 ng-bind-html="globalData.currentTitle"></h1>
You can't two-way bind to a variable in a service, but you can bind to an accessor function. Change your service to return getter and setter functions:
.service('WorkService', ['$sce', function($sce){
var currentTitle= $sce.trustAsHtml('dada');
return {
getCurrentTitle: function(){ return currentTitle; },
setCurrentTitle: function(value){ currentTitle = $sce.trustAsHtml(value);}
};
Then in your controller you can get the currentTitle like this:
$scope.currentTitle = WorkService.getCurrentTitle;
Note that you are setting it equal to the getCurrentTitle function itself (not the result of the function).
Now your html looks like this:
<h1 ng-bind-html="currentTitle()"></h1>
No need to set up $watches or hang stuff of $rootScope. See Demo here.