Angularjs get variable in the view - angularjs

Im trying to catch the variables fromcontroller to use it in the view. but it wont work, but i do know that it exists ( debug on the picture below).
problem: I dont get anything in the view.
note: it might be cause the structure,
main structure is from: https://github.com/meanjs/mean
response:
nothing
my view:
<body class="ng-cloak" ng-controller="HeaderController as aux">
trying to get it to work:
<div class="cometchat_name">{{ varselmessage }} {{ aux.varselmessage }}</div>
function:
(function () {
'use strict';
angular
.module('core')
.controller('HeaderController', HeaderController);
HeaderController.$inject = ['$scope', '$state', 'Authentication', '$rootScope','Socket'];
function HeaderController($scope, $state, Authentication, $rootScope,Socket) {
var aux = this;
$scope.datatest = 200001;
$rootScope.datatest = 900;
$scope.varselmessage = 'varsel';
aux.varselmessage = 'varsel2';
$scope.notifications = [{text: " melding" , image : "kapring"}];
console.log("loaded , maybe possible4?");
}
}());

Problem is with the module, you are missing the dependency injection part [],
angular
.module('core',[])
.controller('HeaderController', HeaderController);
DEMO APP

Related

scope of controllers angularjs

My index.html looks like this:
<body ng-controller="ExternalCtrl">
<div ng-include=" 'header.html' "></div>
<div ng-view></div>
<div ng-include=" 'footer.html' "></div>
<!-- all scripts, angular modules, directives, services etc.. -->
</body>
External controller wrap entire webpage, so I should have access to ExternalCtrl variables wherever in my app for example in headerCtrl which is controller of included header.html file.
I need this because in externalCtrl I get the value from localStorage (which are stored there after success login user) and if its present set a _authentication.isAuth = true; so I can develop my page with ng-if="_authentication.isAuth" for logged in users and ng-if="!_authentication.isAuth" for not logged in.
My externalCtrl code is:
'use strict';
app.controller('ExternalCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
var _authentication = {};
var _authentication = {
isAuth: false
};
var authData = localStorageService.get('authorization');
if(authData) {
_authentication.isAuth = true;
console.log(_authentication.isAuth);
}
}
]);
At this point console.log works correctly and log true if it is true or false if its false obviously.
After that I want to check if I have access to that variable in headerCtrl which is controller of included header.html as I mentioned above. So in this controller i add line:
console.log(_authentication.isAuth);
Which cause following error:
ReferenceError: _authentication is not defined
Why?
Is it correct way of doing this?
It is because _authentication is defined inside the controller. It is not available globally. You can define it on $scope or $rootScope.
function($scope,$rootScope, localStorageService) {
$scope._authentication = {};
$scope._authentication = {
isAuth: false
};
var authData = localStorageService.get('authorization');
if(authData) {
$scope._authentication.isAuth = true;
console.log($scope._authentication.isAuth);
}
}
]);
For more info: AngularJS access parent scope from child controller

passing razor value into angular controller

I've looked at a half dozen examples, but none of them seems to work for me - maybe because of the peculiar var myController = [] format of the code I inherited.
.cshtml:
<div id="ng-app" ng-app="cmorApp">
<div
data-ng-controller="myCtrl"
data-ng-init="referralId = #Model.ReferralId">
...
This works, inasmuch as my page correctly renders the value I seek:
data-ng-init="referralId = 12345"
Now I'm just trying to capture it in my controller.
Controller:
var myCtrl = ['$scope', '$http', 'FileUploader',
function ($scope, $http, FileUploader, referralId) {
console.log(referralId);
//$scope.init = function (referralId) {
// console.log(referralId);
//}
//$scope.init();
It outputs undefined.
What am I missing?
.
UPDATE:
This sort of works:
ng-init="init(#Model.ReferralId)
.
$scope.init = function (referralId) {
$scope.referralId = referralId;
}
The problem is, the value is not there when I need it. It only there if I let the page do some processing.
I can't do this, or I'm back to undefined:
$scope.init = function (referralId) {
$scope.referralId = referralId;
}
console.log($scope.referralId);

How do I do WinJS events the angular way?

There's a nice project for using Angular with WinJS controls together here: https://github.com/winjs/angular-winjs. I already have this working nicely in my app. However it doesn't really cover the use of angular for other parts of WinJS.
I am devloping on a windows 10 phone, and I have code like this:
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
How can I modify my app.onactivated assigment to do things the angular way so I can use $providers and modify $scope variables and so on?
By $providers do you mean the services that angular offers(like $http,$location and so on)?
If so, you can put onactivated method inside the controller callback Definition function(see below codes) so that it can use the angular services.
JS:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var myApp = angular.module("myApp", ["winjs"]);
var myController = myApp.controller("myController", function ($scope) {
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
$scope.$apply(function () {
$scope.test = "The Scope.test has been changed!";
});
}
args.setPromise(WinJS.UI.processAll());
}
};
});
app.start();
})(angular);
HTML:
<body class="win-type-body" ng-app="myApp">
<div ng-controller="myController">
<input type="text" ng-model="test"/>
{{test}}
</div>
If not so, can you tell me what $providers are?

controller function not called from ng-click

I have a controller that ive added a function to but cant get the function to be called from ng-click on an anchor. Ive looked at similar posts but cant really see what I could be missing. Its as though the controller function cant be seen?
The module and controller:
var commonModule = angular.module('common', ['ngRoute', 'ng.ckeditor']);
var mainModule = angular.module('main', ['common']);
//mainModule.config(function ($routeProvider, $locationProvider) {
// $locationProvider.html5Mode(true);
//});
commonModule.factory('viewModelHelper', function ($http, $q, $window, $location) {
return MyApp.viewModelHelper($http, $q, $window, $location);
});
commonModule.factory('validator', function () {
return valJs.validator();
});
mainModule.controller("rootViewModel",
function ($scope, $http, $q, $routeParams, $window, $location, viewModelHelper, $rootElement) {
//test
console.log("creating controller");
var self = this;
viewModelHelper.apiGet('api/PageContent/1', null,
function (result) {
$scope.htmlEditor = result.data;
});
$scope.ToggleEditor2 = function () {
//test
console.log("hello");
if ($scope.editorVisible == true) {
$scope.editorVisible = false;
}
else {
$scope.editorVisible = true;
}
}
});
The controller is referenced at the root level of the page:
Which in this case since im using ASP.Net MVC, is in my _layout.cshtml
<body data-ng-app="main" data-ng-controller="rootViewModel">
In a (mvc) view that gets loaded, I have a button with ng-click that calls the ToggleEditor2 function, but its never called. Cant get a breakpoint to hit in the chrome dev console and I dont see anything written to the log either.
<input type="button" ng-click="ToggleEditor2()" value="test me" />
Update:
If I wrap that anchor with a div and specify the "rootviewModel" controller there, the log message gets written. Hmmm - something tells me its related to scope?
<div data-ng-controller="rootViewModel">
<input type="button" ng-click="ToggleEditor2()" value="test me" />
</div>
Problem
A common problem with $scope is that when using any sort of nested controllers or modules, your $scope's can step on each other and cause issues like you have experienced.
Solution
Using Angular's "Controller As" syntax is the recommended solution for this problem. It allows you to create multiple instances of the same controller, while defining and maintaining a unique scope for each instance.
This Article is a great resource I used to understand and implement this new syntax.

Instantiate other AngularJS-controller with a CommonController when using IIFE

I have a project where a lot of the models are going to be managed by almost the same controller-code with the only exception that they are calling different services.
The way I'm handling this now is by instantiating a Crud-Controller with common code into every custom controller and then redirecting the service-call by changing the variable inside the custom controller. I.e.
vm.service.get() inside the Crud-Controller changes by setting vm.service = teamService; in a custom controller.
This is how I instantiate the Crud-Controller into my custom controllers at the moment:
$injector.invoke(Crud, this, {$scope:$scope});
This works fine, however I don't know if this is the right way to share common controller code. Maybe it is possible to instantiate a service for this use? Because the question I have (if my way of doing it is correct), how do I access other controllers while using IIFE? Right now I am not using IIFE since I have not figured out a way to do so.
I have tried with angular.module('app').controller('Crud') but it does not work.
I.e: How do I get access to the PrimaryCtrl's edit function without using $injector or relying on the $scope inheritance?
http://jsfiddle.net/tcVhN/62/
It looks like your example uses Angular 1.0.x that supports global controllers out of the box. That's how it would be done with more recent Angular, without going too deep into the perils of JS inheritance.
'use strict';
(function (root, angular) {
root.ctrls = root.ctrls || {};
var primaryCtrl = function ($scope) {
var self = this;
console.log('primaryCtrl constructor', self, $scope);
};
primaryCtrl.prototype = {
items: ['Item 1', 'Item 2'],
edit: function (item) {
//do stuff
}
};
primaryCtrl.$inject = ['$scope'];
root.ctrls.primaryCtrl = primaryCtrl;
})(this, angular);
(function (root, angular) {
root.ctrls = root.ctrls || {};
var secondaryCtrl = function ($scope) {
var self = this;
console.log('secondaryCtrl constructor', self, $scope);
};
secondaryCtrl.prototype = angular.extend({},
root.ctrls.primaryCtrl.prototype,
{
items: ['Stuff 1', 'Stuff 2']
}
);
secondaryCtrl.$inject = ['$scope'];
root.ctrls.secondaryCtrl = secondaryCtrl;
})(this, angular);
var app = angular.module('app',[]);
app.controller('PrimaryCtrl', ctrls.primaryCtrl);
app.controller('SecondaryCtrl', ctrls.secondaryCtrl);
and
<div ng-controller="PrimaryCtrl as primary">
<p ng-repeat="item in primary.items">{{item}}</p>
</div>
<div ng-controller="SecondaryCtrl as secondary">
<p ng-repeat="item in secondary.items">{{item}}</p>
</div>
You may also check Angular Classy, which brings opinionated but viable extending syntax to Angular.

Resources