Controller not registered according to console - javascript

For some reason my controller doesn't seem to be registered and I'm honestly not sure why...
I've been following along an AngularJS and Django development course on PluralSight. The only difference between the instructor's stack and mine is that I'm using Angular 1.6.4 and he is using 1.5.0. I've previously hit some errors (like routing syntax), but it's overall been fine.
EDIT:
I should mention that I'm simply following the instructor's instructions and writing the same code as him.
Right now, however, I'm simply stuck. I've got this routing in scrumboard.config.js:
(function () {
"use strict";
angular.module('scrumboard.demo', ["ngRoute"])
.config(["$routeProvider", config])
.run(["$http", run]);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "/static/html/scrumboard.html",
controller: "ScrumboardController",
})
.when('/login', {
templateUrl: "/static/html/login.html",
controller: "LoginController",
})
.otherwise('/');
}
function run($http) {
$http.defaults.xsrfHeaderName = 'X-CSRFToken';
$http.defaults.xsrfCookieName = 'csrftoken';
}
})();
And this controller for login.html:
(function() {
"use strict";
angular.module("scrumboard.demo", [])
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);
function LoginController($scope, $http, $location) {
$scope.login = function () {
$http.post('/auth_api/login/', $scope.user)
.then(function (response){
$location.url("/");
},
function(error) {
//failure
$scope.login_error = "Invalid username or password";
});
};
};
})();
When navigating to localhost:8000/#!/login I can see my form:
<form ng-submit="login()">
<div style="...">{{ login_error }}</div>
<div>
<label>Username</label>
<input type="text" ng-model="user.username"/>
</div>
<div>
<label>Password</label>
<input type="password" ng-model="user.password"/>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
But for some strange reason my console keeps telling me that my LoginController isn't registered.
Could anyone please help me in the right direction?
Sorry if I'm missing any sort of files, but I'm very new to Angular, so I don't really know what to add.
If you need any additional information, please tell me!

remove [] from your controller's defination for login.html.
angular.module("scrumboard.demo")
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);

You are declaring the module scrumboard.demo twice.
Remove the [] in
angular.module("scrumboard.demo")
.controller("LoginController",
["$scope", "$http", "$location", LoginController]);
Without the second argument of angular.module() it is a getter, otherwise it is a setter

In the entry point html, the script tag for file scrumboard.config.js should precede the file controller file. Also as #charlietfl said declaring twice should be removed.
Like this,
<script src="your_path/scrumboard.config.js"></script>
<script src="your_path/scrumboard.controller.js"></script>
Hope this would rectify the problem.

Related

Strange behavior using multiple transclude component in Angularjs 1.6.1

I've a strange behavior using multiple transclude component in Angularjs:
changes in first slot model no visible in controller.
<div ng-app="myApp" ng-controller="testController">
<script type="text/ng-template" id="component-template.html">
<div style="color:red;" ng-transclude="heading">
</div>
<div style="color:blue;" ng-transclude="body">
</div>
</script>
Example1
<input ng-model="example1Model"/>
<test-component>
<panel-heading>
Example2
<input ng-model="example2Model"/>
</panel-heading>
<panel-body>
Example1Result:{{example1Model}}<br/>
Example2Result:{{example2Model}}
</panel-body>
</test-component>
</div>
<script>
angular.module("myApp", [])
.controller("testController", function ($scope, $location) {
})
.component("testComponent", {
templateUrl: "component-template.html",
transclude: {
heading: "panelHeading",
body: "panelBody"
},
controller: function ($scope, $element, $attrs) {
this.$doCheck = function () {
//do anything
}
}
});
</script>
Now if you try to test it in this JSfiddle:https://jsfiddle.net/Lpveophe/1/
Why binding model example2Model did not working?
However example1Model binding model working correctly.
You need to use . in ng-model to make it work. For better understand of scope, please go through this article: https://github.com/angular/angular.js/wiki/Understanding-Scopes
To make it work, replace example2Model with o.example2Model everywhere and change your controller to:
.controller("testController", function ($scope, $location) {
$scope.o = {};
$scope.o.example2Model = '';
})

AngularJs directive not working/visible

I'm just getting started with AngularJs. And I'm trying to implement a login directive. But I don't see the output? I've no errors in my console.
My application structure:
(index.html is not visible)
login.directive.js :
(function() {
'use strict';
angular
.module('lnjapp.login',[])
.directive('login', login);
function login() {
var directive = {
template: '<p>test</p>',
//restrict: 'E',
Controller: LoginController,
controllerAs: 'vm'
};
return directive;
}
})();
app.js :
(function () {
'use strict';
angular.module('lnjapp', ['ngRoute', 'ngCookies', 'angular.filter','lnjapp.login','lnjapp.config'])
.constant('GLOBALS', {
url:'http://domain.dev/api/v1/'
});
$(document).ready(function() {
$.material.init();
});
})();
app/pages/login.html:
<login></login>
--EDIT--
login.controller.js:
(function() {
'use strict';
angular.module('lnjapp.login',[])
.controller('LoginController', LoginController);
function LoginController()
{}
})();
route-config.js:
angular
.module('lnjapp.config',[])
.config(config);
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: '/app/pages/login.html'
});
}
What am I doing wrong here?
You are creating your lnjapp.login twice, once in login.directive.js and again in login.controller.js. The second time the module is created, it overwrites the first, and whatever was created in the first file will no longer be accessible.
You should always only create a module once, and get the already created module to add additional features in all other cases.
Set (create): angular.module('lnjapp.login',[])
Get (consume): angular.module('lnjapp.login')
For more info and other best practices, see John Papa's excellent Angular Style Guide.

JavaScript angular controller get value from scope from another controller

I have school task.
We have a HTML code like this:
<html ng-app="myTest">
<head><script type="text/javascript" src="../myScript.js"></script>
</head>
<body id="tst" class="textpage" ng-controller="TestController as testcon">
<form class="" id="frm" ng-submit="doStuff()">
<div class="form-group">
{{testinfo}}
</div>
<div class="form-group">
<button type="submit" id="sbtn" name="sbtn">testSubmit</button>
</div>
</form>
</body>
</html>
Content of javascript with name myScript.js is this:
var tester = angular.module('myTest', ['ui.mask']);
tester.controller('TestController', ['$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) {
$scope.doStuff = function () {
{
$scope.testinfo = 'unknown value';
};
};
}
]);
I have option to add new javascript.
But I am not possible to get value from $scope.testninfo.
I cannot edit existing JavaScript and cannot edit HTML file. I can just add new javascript.
Is there option how to get value from $scope.testinfo in another javascript?
Thanks.
You can use broadcast
From controller 1 we broadcast an event
$scope.$broadcast('myEvent',anyData);
controller 2 will receive our event
$scope.$on('myEvent', function(event,anyData) {
//code for controller 2
});
here anyData represent your object to be passed
Use ng-model.
<div class="form-group">
<input type="text" ng-model="testinfo">
</div>
I dont think it is possible without appending the existing javascript/html. Because the $scope of the TestController cannot be accessed from another controller (file).
If you COULD append the HTML you could use the $rootscope, in that way the value, which is set by the TestController is accessible from another controller. Or you can add a Global app value. I created a fiddle which show the two options: https://jsfiddle.net/Appiez/wnyb9pxc/2/
var tester = angular.module('myTest', []);
tester.value('globalVar', { value: '' });
tester.controller('TestController', ['$rootScope', '$scope', '$http', '$location', '$window', 'globalVar', function ($rootScope, $scope, $http, $location, $window, globalVar) {
$scope.doStuff = function () {
{
$rootScope.testinfo = 'this is the new value';
globalVar.value = 'a global value';
};
};
}
]);
tester.controller('TestController2', ['$rootScope', '$scope', 'globalVar', function ($rootScope, $scope, globalVar) {
$scope.doStuff2 = function () {
{
alert($rootScope.testinfo);
alert(globalVar.value);
};
};
}
]);
This is what services are for in angular. They ferry data across controllers. You can use NG's $broadcast to publish events that contain data, but Providers, Services, and Factories are built to solve this.
angular.module('krs', [])
.controller('OneCtrl', function($scope, data){
$scope.theData = data.getData();
})
.controller('TwoCtrl', function($scope, data){
$scope.theData = data.getData();
})
.service('data', function(){
return {
getData: function(){
return ["Foo", "Bar"];
}
}
});
Here's a fiddle to help get you into the swing of things. Good luck in school!

Angular issue with $scope and $routeParams

I'm trying to run a function if someone hits the submit button OR there is a value in routeParams (if user hits the page with param already filled out.) I would like a function to run. Im having a brain fart and can't seem to get this to work!
myApp.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/:params?', {
templateUrl: 'myTemplate',
controller : 'myController'
}).otherwise({
redirectTo : '/'
});
} ]);
myApp.controller('ipCntrl', function($scope,$log,$http,$q,$routeParams, $location) {
$scope.runReport = function() {
$location.search({'ip': $routeParams['ip']})
}
});
myApp.controller('myController', function($scope,$log,$http,$q,$routeParams, $location) {
if ($routeParams['ip'])
{
$scope.ip = $routeParams['ip'];
runMyFunction();
}
<div ng-controller="ipCntrl">
<form ng-submit="runReport()">
<input class="form-control" ng-model="ip">
</form>
<div ng-view ></div>
</div>
<script type="text/ng-template" id="myTemplate">
HI!
</script>
Since you're trying to call a function on button click or on initialization after checking the $routeParams, just include that code in the angular controller you are using (ipCntrl)
myApp.controller('ipCntrl', function($scope,$log,$http,$q,$routeParams, $location) {
$scope.runReport = function() {
$location.search({'ip': $routeParams['ip']})
}
//Just put the if statement here
//you're already using the ng-submit to call this function from your form
if ($routeParam.ip != null) //other definition check logic
$scope.runReport();
});
You can use...
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
console.log('toState ->');
console.log(toState);
console.log('toParams ->');
console.log(toParams);
console.log('fromState ->');
console.log(fromState);
console.log('fromParams ->');
console.log(fromParams);
runMyFunction();
})
...in your controller's function to intercept state transitions and requested URls ($stateParams).
See State Change Events.
You also have View Load events that may be useful.
You can also intercept state changes (and evaluate requested routes) in Angular's .run().
See .run() ui-router's Sample App.

AngularJS Controller depending on URL parameter

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.
I start to learn AngularJS and I have a very simple question :
Depending on ID contained in URL, I would like to display different BD record.
...
<div ng-app=MyApp>
<div ng-controller="MyCtrl">
{{ record }}
</div>
</div>
...
My Javascript file :
var MyApp = angular.module("MyApp",[]);
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/get/:productId', {
controller: 'MyCtrl'
});
}])
MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
function($scope,$routeParams,$http) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
}])
I tried to use $routeProvider and $routeParams without success.
Thank you in advance,
Bill
you need 2 things , the $routeParams injected in your controller and create a valid route with the get method
MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
function($scope,$http,$routeParams) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
};

Categories

Resources