I'm trying to initialize a test.service.js from an angular1.5 component and I don't really know how to that. I have used this structure for angular components:
var testComponent = {
templateUrl: "app/components/test.component.html",
controllerAs: "mvm",
bindings:{
bindingInput: "=",
},
controller: function(){
var mvm = this;
}
};
angular.module('myApp').component('testComponent', testComponent);
Just inject it using the controller as following :
...
},
controller: ['testService', function(testService){
var mvm = this;
}],
...
You can inject the service right into the controller like this:
....
controller: function(testService) {
var mvm = this;
}
};
To prevent testService getting obfuscated by a minification plugin, let the injector service know about the dependencies as well.
var Controller = function(testService) {
// Your controller code here
};
Controller.$inject = ['testService'];
var testComponent = {
...
controller: Controller, // Assign controller in component
...
};
Related
Students.html
<div class="row">
<student info="ui.Ram"></student>
</div>
Student.directive Template
<h1>{{ui.name}}</h1>
Route Config
app.config(urlRouter);
function urlRouter($routeProvider, $locationProvider) {
$routeProvider
.when('/students', {
templateUrl: 'app/views/students.html',
controller: 'prodCtrl',
controllerAs: 'ui'
})
}
Custom Directive
app.directive('student', "student");
function student() {
var directive = {};
directive.restrict = 'E';
directive.templateUrl = "Student.directive.html";
directive.scope = {
ui : "=name"
}
return directive;
});
Controller
app.controller('StudentController', StudentController);
function StudentController($scope) {
$scope.Ram= {};
$scope.Ram.name = "Mahesh";
};
When I do this way, name ("Mahesh") is reflected in UI.
I am thinking to do the same without injecting $scope in the controller.
Something like this.
function StudentController() {
var vm = this;
vm.Ram= {};
vm.Ram.name = "Mahesh";
return vm;
};
But the value is not reflecting.
You need to use controller as syntax in view to do that:
<div ng-app = "app" ng-controller = "StudentController as ctrl">
<student name = "ctrl.Ram"></student>
</div>
I have a component :
import template from './login.html';
import controller from './login.controller';
import './login.less';
let loginComponent = {
restrict: 'E',
bindings: {
redirect: '#'
},
template,
controller,
controllerAs: 'vm'
};
export default loginComponent;
Which uses a basic controller:
import angular from 'angular';
let LoginController = [
'AuthService',
'$resource',
'$state',
'config',
(AuthService, $resource, $state, config) => {
var vm = {
redirect: ''
};
var initialize = () => {
if (AuthService.authenticated()) {
loginSuccess();
}
};
var loginSuccess = () => {
console.log(vm.redirect);
if (vm.redirect) {
$state.go(vm.redirect);
}
};
initialize();
return vm;
},
];
export default LoginController;
The issue is that the redirect attribute is not available at the time of construction (when the initialize method is called). How do I access this attribute during controller construction? If there is no way, what's the best way to watching for this attribute to become available, and then calling the initialize function?
Solution:
$onInit was exactly the method I was looking for. Here's the corrected controller for future users:
import angular from 'angular';
let LoginController = [
'AuthService',
'$resource',
'$state',
'config',
(AuthService, $resource, $state, config) => {
var vm = {
redirect: ''
};
vm.$onInit = () => {
if (AuthService.authenticated()) {
loginSuccess();
}
};
var loginSuccess = () => {
console.log(vm.redirect);
if (vm.redirect) {
$state.go(vm.redirect);
}
};
return vm;
},
];
export default LoginController;
You can't access the binding at controller construction because of how Angular directive linking works.
It will be available in link function in directive, in component (which is sugar syntax for directive) it is available in magic $onInit controller method:
Called on each controller after all the controllers on an element have
been constructed and had their bindings initialized (and before the
pre & post linking functions for the directives on this element). This
is a good place to put initialization code for your controller.
The problem with listed controller is that it uses arrow function instead of regular one. The controller is an instance of controller constructor and provides this context.
There is no need to invent initialize method, it should be this.$onInit now.
I am relatively new to angularJS, I am trying to set up a page where inturn multiple pages are called depending upon the selection made previously.
All the pages have their own controller, so I am trying to set the controller and view src through the javascript and using them in HTML tags.
Following is what I am doing:
HTML page:
<div ng-if="sidebarName=='sidebar-device-wire'">
<div ng-controller="getSidebarCtlr">
<div ng-include src="sidebarSrc"></div>
</div>
</div>
javascript:
$scope.sidebarSrc="views/sidebars/sidebar-device.html";
$scope.sidebarCtlr="SidebarDeviceCtrl";
$scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}
For some reason though, this does not work. i can get the HTML page but the controller is not being called. Can anyone please tell me what I am doing wrong?
I would also recommend to use ngRoute or ui.router because there are many features that aren't easy to implement from scratch (like named views, nested views / nested states or resolves) and these modules are well tested.
Not sure why your controller isn't running but I guess that the expression of the controller is evaluated before your controller that is setting the name is running. So it will be always undefined at compile time.
But if you really like to implement a very basic router you could do it like in the following demo (or in this fiddle).
Update 21.12.2015
Here are some router examples that I wrote for other SO questions:
simple ui.router example - jsfiddle
more complex nested state example ui.router - jsfiddle
dynamic link list with ngRoute - jsfiddle
Please also have a look at ui.router github pages to learn more about it.
angular.module('simpleRouter', [])
.directive('simpleView', simpleViewDirective)
.provider('simpleRoutes', SimpleRoutesProvider)
.controller('MainController', MainController)
.controller('HomeController', HomeController)
.config(function(simpleRoutesProvider) {
simpleRoutesProvider.state([{
url: '/',
templateUrl: 'home.html',
controller: 'HomeController'
}, {
url: '/view1',
templateUrl: 'view1.html'
}, {
url: '/view2',
templateUrl: 'view2.html',
controller: function($scope) {
$scope.test = 'hello from controller'
}
}]);
simpleRoutesProvider.otherwise('/');
})
function HomeController($scope) {
$scope.hello = 'hello from home controller!!';
console.log('home controller started')
}
function MainController($scope) {
$scope.hello = 'Main controller test';
}
function simpleViewDirective() {
return {
restrict: 'EA',
scope: {},
template: '<div ng-include="templateUrl"></div>',
controller: function($scope, $location, $controller, simpleRoutes) {
var childControllerInst;
$scope.templateUrl = simpleRoutes.currentRoute.templateUrl || simpleRoutes.otherwise.templateUrl;
$scope.$watch(function() {
return $location.path();
}, function(newUrl) {
//console.log(newUrl)
$scope.templateUrl = simpleRoutes.changeRoute(newUrl);
childControllerInst = $controller(simpleRoutes.currentRoute.controller || function() {}, {$scope: $scope});
});
$scope.$on('$destroy', function() {
childControllerInst = undefined;
})
},
link: function(scope, element, attrs) {
}
}
}
function SimpleRoutesProvider() {
var router = {
currentRoute: {
templateUrl: ''
},
states: [],
otherwise: {},
changeRoute: function(url) {
var found = false;
angular.forEach(router.states, function(state) {
//console.log('state', state);
if (state.url == url) {
router.currentRoute = state;
found = true;
}
});
if (!found) router.currentRoute = router.otherwise;
//console.log(router.currentRoute);
return router.currentRoute.templateUrl;
}
};
this.state = function(stateObj) {
router.states = stateObj;
};
this.otherwise = function(route) {
angular.forEach(router.states, function(state) {
if (route === state.url ) {
router.otherwise = state;
}
});
//console.log(router.otherwise);
};
this.$get = function simpleRoutesFactory() {
return router;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="simpleRouter" ng-controller="MainController">
<script type="text/ng-template" id="home.html">home route {{hello}}</script>
<script type="text/ng-template" id="view1.html">view1</script>
<script type="text/ng-template" id="view2.html">view2 {{test}}</script>
<div simple-view="">
</div>
home
view1
view2
<br/>
{{hello}}
</div>
What's that code means? $scope.getSidebarCtlr = function(){return $scope.sidebarCtlr;}
the ng-directive requires a Controller name, its argument type is string and you cannot pass a simple function, you need to register a valid controller associating it to a module via the controller recipe.
https://docs.angularjs.org/guide/controller
angular.module('test', []).controller('TestCtrl', function($scope) {
$scope.greetings = "Hello World";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section ng-app="test">
<article ng-controller="TestCtrl">{{ greetings }}</article>
</section>
I am new to AngularJS. In my project I have a search screen when search I will get the search result in the ngGrid.
On click of any row in the grid, it should populate the details of that row in other page. Basically, I need to pass the ID of the selected record to the other page. I don't know how to handle this in AngularJS (I am using AngularJS HotTowel template) and Breeze for data access logic.
Appreciate if you could provide me link or any where it is implemented which I could refer.
You can create service and share values for instance
var myApp = angular.module('myApp', []);
myApp.factory('ShareData', function() {
var shared;
return {
setValue: function(val){
shared = val;
},
getValue: function(){
return shared;
}
});
function FirstCtrl($scope, ShareData){
ShareData.setValue(1);
}
function SecondCtrl($scope, ShareData){
$scope.data = ShareData.getValue();
}
You need $routeParams for this.
Below is an example of the routing configuration:
var app = angular.module("app", ["ngRoute"])
.config(["$routeProvider", function ($routeProvider) {
$routeProvider
.when("/", {
controller: "HomeController",
templateUrl: "/home/main",
})
.when("/products/:category", {
controller: "ProductController",
templateUrl: "/product/index"
})
.otherwise({
redirectTo: "/"
});
}]);
Product Controller
angular.module("app")
.controller("ProductController",["$scope","$routeParams", function($scope,$routeParams){
$scope.category = $routeParams.category;
alert($scope.category);
}]);
'Main' View
<a ng-href="#/products/ladies">Ladies</a>
check this URL for more info:
https://docs.angularjs.org/api/ngRoute/service/$routeParams
I have an issue communicating from my application to a module i have created. I have create an AngularJS module below.
(function (document, window) {
'use strict';
var piCart = angular.module('piCart', []);
piCart.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/cart', {
templateUrl: "packages/pi-cart/segments/cart.html",
controller: 'CartController',
private : true
}).
when('/checkout', {
template: "Checkout Page",
// controller: 'CartController',
private : true
});
}]);
piCart.factory('TestFactory', function(){
return{
test : function(){
return 'test works';
}
}
});
piCart.controller("CartController",function(TestFactory){
console.log("Cart Controller Running");
console.log(TestFactory.test());
});
})(document, window);
This is loaded into my main application as so
var app = angular.module('app', ['ngRoute', "ui.bootstrap", "googlechart", "piCart"]);
Im trying to call the module TestFactory from the app.controller like so
app.controller('ProductController',function($scope){
$scope.addToCart = function(id){
//alert("clicked: "+id);
test = TestFactory.test();
console.log(test);
};
});
But im getting the error
ReferenceError: TestFactory is not defined
I believe you're getting that error because you did not inject TestFactory in the controller:
app.controller('ProductController', function($scope, TestFactory) {
// your code...
});