Angularjs: how to use "this" instead of $scope - angularjs

I would like to work out how to convert this:
app.controller('AnswersCtrl', ['$scope', '$http', '$log', '$ionicModal', '$state', 'SuspectService',
function($scope, $http, $log, $ionicModal, $state, SuspectService) {
$scope.suspects = [];
SuspectService.getSuspects().then(function(data){
$scope.suspects = data;
});
$scope.goToClues = function(){
$state.go('clues')
};
}]);
into something that looks like this:
app.controller('AnswersCtrl', ['$http', '$log', '$ionicModal', '$state', 'SuspectService',
function($http, $log, $ionicModal, $state, SuspectService) {
var self = this;
self.suspects = [];
SuspectService.getSuspects().then(function(data){
self.suspects = data;
});
self.goToClues = function(){
$state.go('clues')
};
}]);
The code which utilises $scope works but the code which utilises this (self) doesn't.
I have tried a couple of variations and haven't been able to get it to work.

It looks like you are almost there in order for this syntax to work in your controllers you also need to change the markup where you define the controller to look like this:
<div ng-controller="AnswersCtrl as vm">
{{ vm.suspects[0].name}}
</div>
You can see a working example without the extra services you have defined in you example here: http://jsbin.com/zevaluside/3/edit
You will also require Angular 1.2 or higher for this to work as well.

Related

AngularJs sanitizing input

I am using angular 1.6.4
var app = angular.module('a', ['ngSanitize']);
app.controller('BaseController', function($scope, $sce) {
$scope.str = "<script>alert('hello world')</script>";
$scope.sanitized = $sce.trustAsHtml($scope.str);
});
I am trying to get a sanitized form of a string as the one above but it always returns the same $scope.str. What am I doing wrong here? Thanks-
This also did not remove the script tags
app.controller('BaseController', ['$scope', '$sce', function( $scope, $sce) {
$scope.str = "<script>alert('hello world')</script>";
$scope.sanitized = $sce.trustAsHtml($scope.str);
}]);
A small glitch in your code that $sce should be injected in the controller level.
app.controller('BaseController', ['$sce', function($sce) {
// ... [your code]
}]);

how to passing data from one controller to another controller using angular js 1

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
code Page1.html
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
now i want to show scope message into page2 controller
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
You can use $rootScope instead of $scope:
// do not forget to inject $rootScope as dependency
$rootScope.Message="Hi welcome";
But the best practice is using a service and share data and use it in any controller you want.
You should define a service and write getter/setter functions on this.
angular.module('app').service('msgService', function () {
var message;
this.setMsg = function (msg) {
message = msg;
};
this.getMsg = function () {
return message;
};
});
Now you should use the setMeg function in Controller1 and getMsg function in Controller2 after injecting the dependency like this.
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
$scope.Message="Hi welcome"
msgService.setMsg($scope.Message);
}]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
///here i want get that scope value
console.log('message from contoller 1 is : ', msgService.getMsg());
}]);
You should use services for it .
Services
app.factory('myService', function() {
var message= [];
return {
set: set,
get: get
}
function set(mes) {
message.push(mes)
}
function get() {
return message;
}
});
And in ctrl
ctrl1
$scope.message1= 'Hi';
myService.set($scope.message1);
ctrl2
var message = myService.get()
Sharing data from one controller to another using service
We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('Controller1', ['setGetData',function(setGetData) {
// To set the data from the one controller
$scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

AngularJs multiple Controllers, ng-click and ng-view

This might be me just missing something or getting the wrong end of the stick on the tutorial, so bear with me.
I have my app....
var shepApp = angular.module('shepApp', [
'ngRoute',
'ui-notification',
'shepControllers',
'shepFilters',
'shepServices'
]);
shepApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/galaxies', {
templateUrl: "partials/galaxies.html",
controller: 'GalaxyListCtrl'
}).
}]);
And my controllers go something like this....
var shepControllers = angular.module('shepControllers', []);
shepControllers.controller('GalaxyListCtrl', ['$scope', '$location', 'Notification', 'Galaxy', function($scope, $location, Notification, Galaxy) {
$scope.galaxys = Galaxy.query();
$scope.blah = function(){
alert(123);
}
}]);
shepControllers.controller('GalaxyDetailCtrl', ['$scope', '$routeParams', '$location', 'Notification', 'Galaxy', function($scope, $routeParams, $location, Notification, Galaxy) {
$scope.galaxy = Galaxy.get({slug: $routeParams.slug});
}]);
My galaxies.html partial contains the following HTML using ng-click.
<button ng-click="blah"></button>
My thinking was that that blah function for the click event would be exposed when my route is /galaxies and the controller in use is GalaxyListCtrl - but the alert is never fired at all.
I think I am missing something in the way this all fits together.
Calling a function without arguments is done using the name of the function followed by parentheses:
ng-click="blah()"

Can I have two angular.module calls to the same ng-app in two different files for same controller?

Hi I have created two angulerjs files for same ng-app example.
admin.js
var app = angular.module('arcadminmodule', ['ngTable', 'ui-notification']);
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
admin1.js
var app = angular.module('arcadminmodule');
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
But its overriding admin.js from admin1.js
please help me out....
In admin1.js when you write:
var app = angular.module('arcadminmodule');
you are not creating a new module. You are trying to get an existing module named 'arcadminmodule'.. If you want to create a new module, you will have to write something like this:
var app = angular.module('arcadminmodule',[]); // add your depencencies...
Now, In your case, in admin.js you are creating your module and admin1,js you are making use of the same module. In angular you cannot have two controllers with the same name. Controllers are for (from the docs):
Set up the initial state of the $scope object.
Add behavior to the $scope object.
So If you need are trying to apply some roles or some business logic, It need to go into one controller. Make sure your controller contain only the business logic needed for a single view.
I think its no need for use the same controller in two places.But you can use services in places.If you need to do some think different from the ArcAdminController,use this structure.
Services
-service1.js
(function (angular) {
angular.module('marineControllers').service('boatService', function (ajaxService) {
}
)
-service2.js
-module..js
var artistControllers = angular.module('marineControllers',['ngAnimate']);
Controllers
-controller1
(function (angular) {
angular.module('marineControllers').controller("BoatController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'boatService', 'autocompleteFactory', 'utilityFactory',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, boatService, autocompleteFactory, utilityFactory) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
-controller2
(function (angular) {
angular.module('marineControllers').controller("DeviceController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'deviceService', 'autocompleteFactory', 'utilityFactory','commonDataService',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, deviceService, autocompleteFactory, utilityFactory,commonDataService) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
I have been use many services in both controllers,still they are different logics.

Setting AngularJS global values for accessing and setting across controllers

I have been experimenting with AngularJS values, and wish to store a global value for accessing and setting in different controllers.
So I have been trying out with the value approach like so:
var app = angular.module('myApp', []);
app.value('globalValue', 0);
app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.updateValue = function() {
globalValue++;
};
}]);
app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.someValueB=globalValue;
}]);
Here's a fiddle
This is not working as I thought it might, so in my fiddle, when clicking the button to increment my 'global', the scope property in myCtrlB does not change.
I have clearly gone about this the wrong way, have I totally misunderstood how to use value()'s here?
Thanks
This code should work basically you need an object so both controllers are pointing at the same object and some property of that object is changed. Otherwise you are assigning the initial value of globalValue to some local variable but it's not a reference.
var app = angular.module('myApp', []);
app.value('globalValue', {counter:0});
app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.updateValue = function() {
globalValue.counter++;
};
}]);
app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.someValueB=globalValue;
}]);
Updated fiddle: http://jsfiddle.net/kfxy5hs1/3/

Resources