How do I create an active (class) using angular.js - javascript

I am using [uikit] and like to utilize their active class on a link. I'd also like to use their icons simultaneously. 1 I am trying to implement this practice, fiddle however I get this error.
Uncaught SyntaxError: Unexpected token .
and
`Uncaught Error: [$injector:modulerr]
Failed to instantiate module rustyApp due to:
Error: [$injector:nomod] Module 'rustyApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.`
This is my HTML:
<section class="top-bar-section uk-navbar-flip" ng-app="link">
<ul class="uk-navbar-nav ">
<li active-link="uk-active"><i class="uk-icon-home uk-icon-medium "> </i>home</li>
<li active-link="uk-active"><i class="uk-icon-photo uk-icon-medium "></i> work</li>
<li active-link="uk-active"><i class="uk-icon-envelope-o uk-icon-medium "></i> contact</li>
</ul>
</section>
// create the module and name it rustyApp
var rustyApp = angular.module('rustyApp', [
'ngRoute',
'viewController',
'mm.foundation',
'angular-flexslider'
])
.controller('BasicSliderCtrl', function($scope) {
$scope.slides = [
'../images/sliderContent/1.jpg',
'../images/sliderContent/2.jpg',
'../images/sliderContent/3.jpg',
'../images/sliderContent/4.jpg'
];
});
// route for the home page
rustyApp.config(function($locationProvider, $routeProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/home', {
templateUrl: 'partials/home.html',
controller: 'HomeController'
})
.when('/work', {
templateUrl: 'partials/work.html',
controller: 'WorkController'
})
.when('/contact', {
templateUrl: 'partials/contact.html',
controller: 'ContactController'
})
.otherwise({
redirectTo: '/home'
});
});
var viewController = angular.module('viewController', []);
var viewController = angular.module('viewController', []);
.directive('activeLink', ['$location', function(location) {
return {
restrict: 'A',
link: function(scope, element, attrs, controller) {
var clazz = attrs.activeLink;
var path = attrs.href;
path = path.substring(1); //hack because path does bot return including hashbang
scope.location = location;
scope.$watch('location.path()', function(newPath) {
if (path === newPath) {
element.addClass(clazz);
} else {
element.removeClass(clazz);
}
});
}
};
}]);
rustyApp.controller('HomeController', function($scope) {});
rustyApp.controller('WorkController', function($scope) {});
rustyApp.controller('ContactController', function($scope) {});
var OffCanvasDemoCtrl = function($scope) {};
I suspect I am not hooking the .directive correctly or not including a controller but if you look at the fiddle there isn't one!
UPDATE:
I wound with the following:
HTML
<section class="top-bar-section uk-navbar-flip">
<ul class="uk-navbar-nav ">
<li my-active-link="/"><i class="uk-icon-home uk-icon-medium "> </i>home</li>
<li my-active-link="/work"><i class="uk-icon-photo uk-icon-medium "></i> work</li>
<li my-active-link="/contact"><i class="uk-icon-envelope-o uk-icon-medium "></i> contact</li>
</ul>
</section>
JS
rustyApp.directive('myActiveLink', function($location) {
return {
restrict: 'A',
scope: {
path: "#myActiveLink"
},
link: function(scope, element, attributes) {
scope.$on('$locationChangeSuccess', function() {
if ($location.path() === scope.path) {
element.addClass('uk-active');
} else {
element.removeClass('uk-active');
}
});
}
};
});

You just need to change .directive(... to rustyApp.directive(... and take it outside of the config function.
This line causes the first JS error which causes rustyApp to fail to load as you have it inside the config for some reason.
I think you've misunderstood what's going on so I'll just write up this little example here:
```
rustyApp = angular.module(...).controller(...);
// Same result as below. IMO you should use the below generally as it is clearer.
rustyApp = angular.module(...);
rustyApp.controller(...);
```
Also directive, config, run, factory, service, controller (and any I've forgotten) are all functions that are available on a module 'object'. When you call one of them the result of the function is the module you called it on.

Related

Lazy loading angular app doesn't load a directive

I'm trying to lazy load a directive in my angular app, using ui.router and oc.lazyLoad. Here is my code :
menu :
<ul>
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="demo">Demo</a></li>
<li><a ui-sref="test">Test</a></li>
</ul>
<ui-view></ui-view>
route config :
angular.module('app', ['ui.router', 'oc.lazyLoad'])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state("demo", {
url:'/demo',
views: {
'lazyLoadView' : {
template: '<demo-directive></demo-directive>'
}
},
resolve : {
loadDemoModule : ['$ocLazyLoad', function($ocLazyLoad) {
console.log('resolving demo lazy load');
return $ocLazyLoad.load('demo.js');
}]
}
})
.state("home", {
templateUrl : 'core/home.html',
url : '/home'
})
}])
and the directive :
angular.module('app').
directive('demoDirective', function() {
return {
restrict: 'E',
scope: {},
template: require('./demo-directive.html'),
// templateUrl: 'demo-directive.html',
controllerAs: 'demo',
controller : ['$timeout', function($timeout) {
console.log('in directive controller');
}]
};
});
I have no errors, the console.log in resolve function is displayed, the demo.js file is loaded but then noting is happening, console form directive controller is not displayed. I'm trying to follow the first example from ocLazyLoad example
Thanks
How about lazy loading this way.
return $ocLazyLoad.load({
name: 'app.demo',
files: ['path/to/demo.js']
})
You have not declared the oc.lazyLoad module as a dependency.
angular.module('app.demo', ["oc.lazyLoad"])
See the quickstart - https://oclazyload.readme.io/docs/
You're also not closing your demo directive
template: '<demo-directive></demo-directive>'

Collapsible menu isn't working - Argument 'SidebarController' is not a function, got undefined

I'm working on making a collapsible menu with Angular, but it seems to have broken the rest of my webpage! I've isolated it to be somewhere in my app.js file, which controls everything. I get the error stated in the title:
Error: [ng:areq] Argument 'SidebarController' is not a function, got undefined.
'use strict';
(function() {
// Declare app level module which depends on views and components
angular.module('app', [
'ngRoute',
'app.view1',
'app.view2',
'app.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);
//Sidebar toggle
app.controller('SidebarController', function($scope) {
$scope.state = false;
$scope.toggleState = function() {
$scope.state = !$scope.state;
};
});
app.directive('sidebarDirective', function() {
return {
link : function(scope, element, attr) {
scope.$watch(attr.sidebarDirective, function(newVal) {
if(newVal)
{
element.addClass('show');
return;
}
element.removeClass('show');
});
}
};
});
}())
And here's the relevant <div> that contains the sidebar:
<div id="page-wrapper" ng-class="" ng-cloak>
<div id="sidebar-wrapper" ng-controller="SidebarController" class="sidebar" sidebar-directive="state">
<a id="navigation-toggle" ng-click="toggleState()">MENU</a>
<ul class="navigation">
<li class="navigation-items">
Denon Settings
</li>
<li class="navigation-items">
Light Settings
</li>
</ul>
</div>
What's going on?
I got it! The problem was that I did not properly define app. The declaration should read:
// Declare app level module which depends on views and components
var app = angular.module('app', [
'ngRoute',
'app.view1',
'app.view2',
'app.version'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]);

Display current category name in breadcrumbs (using angularJS)

I'm struggling to make my category and vendor name visible on breadcrumbs.
I'm using ng-breadcrumbs module (https://github.com/ianwalter/ng-breadcrumbs).
I guess I have problem with making curCategory and curVendor globally acessible, but tried some ways and can't make it working.
Here is my html:
<body ng-controller="mainController as main">
(...)
<ol class="breadcrumb">
<li ng-repeat="breadcrumb in breadcrumbs.get({'Category':curCategory,'Vendor': curVendor}) track by breadcrumb.path" ng-class="{ active: $last }">
<a ng-if="!$last" ng-href="#{{ breadcrumb.path }}" ng-bind="breadcrumb.label" class="margin-right-xs"></a>
<span ng-if="$last" ng-bind="breadcrumb.label"></span>
</li>
</ol>
My routes:
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/pages/main.html',
label: 'Home'
}).
when('/:cat', {
templateUrl: 'templates/pages/category.html',
label: 'Category'
}).
when('/:cat/:ven', {
templateUrl: 'templates/pages/vendor.html',
label: 'Vendor'
}).
otherwise({
redirectTo: '/'
});
}]);
My controller:
var app = angular.module("myApp", [
'ngRoute',
'ng-breadcrumbs'
]);
app.controller('mainController', function($scope, $routeParams, breadcrumbs) {
$scope.breadcrumbs = breadcrumbs;
$scope.curCategory = $routeParams.cat;
$scope.curVendor = $routeParams.ven;
(...)
});
Uff I found what was wrong!
What suprised me was that inside specific controllers it worked fine, but when I moved it to mainController it returned empty object from $routeParams.
Here is solution:
$scope.$on('$routeChangeSuccess', function() {
$scope.curCategory = $routeParams.cat;
$scope.curVendor = $routeParams.ven;
});
It just assigned variables before $routeParams were populated.

My Angular ui modal cant find the template

here is my app , trying to use UI modal, but when the modal function cant find the html template. i can console log inside the function, but cant open a modal view.
var app = angular.module('myApp', [
'angularUtils.directives.dirPagination',
'ui.bootstrap'
]);
app.controller('galleryCtrl', ['$scope', '$http', function ($scope, $http) {
}]).
controller('ModalInstanceCtrl',['$scope','$modal',function($scope, $modalInstance){
}]).
directive('myGallery', function ($http,$modal) {
return {
restrict: 'E',
scope: {
feed: '#',
search: '=?',
resultsPerPage: "=?",
sorting: "=?"
},
templateUrl: './MyGallery.tpl.html',
link: function (scope, element, attrs) {
scope.search = scope.search || true;
scope.sorting = scope.sorting || true;
scope.resultsPerPage = scope.resultsPerPage || 10;
console.log(scope.resultsPerPage);
scope.openModal = function() {
var modalInstance = $modal.open({
templateUrl: '/views/modal.html',
controller: 'ModalInstanceCtrl'
});
};
in the html:
<div class="imgs">
<ul>
<li dir-paginate="img in imgs
| filter:query
| itemsPerPage: resultsPerPage.value || 10 ">
<img ng-src="{{img.url}}" ng-click="openModal()">
</li>
</ul>
</div>
and this is what i get :
GET http://localhost:63342/views/modal.html 404 (Not Found)
the path is 100% correct , so if u guys can see what is the problem.
Just to make sure.. try:
templateUrl: 'views/modal.html',
Maybe your local server's document root it's not where you think it is.
Getting rid of the initial slash you make sure the path is relative to the root folder of your angular project.

Angularjs routing fails on server when minification is turned on

I am currently building a Angularjs singel page application and i have run in to some odd error with my routing.
I have a nav bar with multiple options and all but one of them work correct.
This is my route provider.
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when("/index", {
templateUrl: "/App/Views/index.html",
controller: "IndexController"
})
.when("/log", {
templateUrl: "/App/Views/log.html",
controller: "LogController"
})
.when("/help", {
templateUrl: "/App/Views/help.html",
controller: "HelpController"
})
.when("/login", {
templateUrl: "/App/Views/login.html",
controller: "LoginController"
})
.when("/signup", {
templateUrl: "/App/Views/signup.html",
controller: "SignupController"
})
.when("/logout", {
templateUrl: "/App/Views/logout.html",
controller: "LogOutController"
})
.when("/user", {
templateUrl: "/App/Views/user.html",
controller: "UserController"
})
.otherwise({
redirectTo: "/index"
});
}]);
And this is my Navbar
<li>
Hem
</li>
<li ng-class="{ activeLink: isActive('/log')}" data-ng-hide="!isLoggedIn">
Logg
</li>
<li ng-class="{ activeLink: isActive('/help')}" data-ng-hide="!isLoggedIn">
Hjälp
</li>
<li ng-class="{ activeLink: isActive('/logout')}" data-ng-hide="!isLoggedIn">
Logga ut
</li>
<li ng-class="{ activeLink: isActive('/user')}" data-ng-hide="!isLoggedIn">
{{userName}}
</li>
And my problem is that when i click the {{userName}} link i am taken to the index page.
And this error only occurs on the live server when the js is minified, if it is unminified on the server so does it work like intended.
If i run this site localy i can use both the regular version and the minified one and the routing behaves like intended.
The console does not show any errors when i click on the link and whn i inspect the html in chrome so does it have the correct html
Johan Karlsson.
I have tried pointing the {{userName}} link to "#/log" and it worked fine.
Here is my user controller
(function () {
var app = angular.module("connectPortal");
var userController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from HelpController";
}];
app.controller("UserController", userController);
}());
And this is my log controller
(function () {
var app = angular.module("connectPortal");
var logController = ['$scope', 'authService', function ($scope, authService) {
authService.authenticateUser();
$scope.var = "var variable from LogController";
}];
app.controller("LogController", logController);
}());

Categories

Resources