Adding a new Angular Dependancy - javascript

I'm new to angular and I think I'm doing this right but I'm not sure. I just got pushed into a project without much help and I'm trying to figure this out. I need to make some data using a tree view. The old code was using ng-repeat so I need to do something like that. I found a library that can help with that called treeRepeat. I have 0 experience using npm or bower so I just downloaded "module.js" and "tree-repeat.js" and added it to the project and then added it to a bundle and called it in my html page but I get a error injecting module error and I can't figure out why.
I have the error link at bottom but its a huge link and I have no idea on how to hyperlink it.
App.js
var app = angular.module('app', ['angularFileUpload', 'ngSanitize', 'ui.mask', 'ui.select', 'ui.bootstrap', 'ui.bootstrap.tpls', 'angular.filter', 'smart-table', 'colorpicker.module', 'sf.treeRepeat'])
.config(function ($httpProvider) {
//make delete type json to facilitate passing object
//to our generic method.
$httpProvider.defaults.headers["delete"] = {
'Content-Type': 'application/json;charset=utf-8'
};
});
EDIT: New error when I changed the bundle order. It now goes jquery first, treerepeat, and then angularjs.
https://docs.angularjs.org/error/$injector/nomod?p0=sf.treeRepeat
Calling code:
<div class="row">
<ul>
<li sf-treepeat="role in vm.roles">
{{role.RoleName}}
<ul>
<li sf-treecurse></li>
</ul>
</li>
</ul>
Bundle Order (The 2 files I added with tree-repeat are at the end of the angularjs bundle:
#section scripts {
#Scripts.Render("~/bundles/manageUser")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/angularjs")
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
});
</script>
}

Related

My page turns blank when I try to use a controller in angular

I have a problem with angular to integrate a controller to my page. The page becomes blank as soon as I try to integrate it.
<div class="container-fluid" ng-app="ods-widgets" ng-controller="myCtrl" >
<ods-dataset-context context="cont" cont-domain="https://data.rennesmetropole.fr" cont-dataset="{{dataset}}">
</ods-dataset-context>
</div>
<script>
var app = angular.module("ods-widgets", []);
app.controller("myCtrl", function($scope) {
$scope.dataset= "statistiques-de-frequentation-du-site-rennes-metropole-en-acces-libre";
});
</script>
Without the controller:
http://jsfiddle.net/5c0xr8f4/13/
With the controller:
http://jsfiddle.net/8796ueyL/
ods-dataset-context is a component (https://github.com/opendatasoft/ods-widgets).
it's a component that I import via CDN.
I just want to control what is inside the cont-dataset
I looked into the library that you mentioned in your comment. It seems that the issue is that ods-widgets is already an angular module that is being imported via the CDN. If you name your own angular module with the same name, you are effectively overwriting this existing module that you have imported. So what you want to do is declare your own angular module and import ods-widgets as a dependency. You can take a look at the Fiddle for a working sample, but the important part is this one:
angular.module("myApp", ['ods-widgets']);
And in your HTML update the ng-app reference:
<div class="container-fluid" ng-app="myApp" ng-controller="myCtrl" >

How can I read URL parameters in AngularJS?

I'm trying to make a blog using AngularJS. The home page queries a third party service of mine that returns an array of all my articles/posts. I am displaying shortened versions of these posts on the home page, and want to have "read more" under each post that passes that post's ID through a URL parameter to another HTML page:
index.html:
<div ng-controller="blogCtrl" id="blog">
<div class="post" ng-repeat="post in posts">
<div class="header">
<h1>{{ post.fields.title }}</h1>
<p class="date">{{ post.sys.createdAt | date}}</p>
</div>
<p>{{ post.fields.body | cut:true:1600:' ...'}}</p>
read more
</div>
</div>
What do I need to do in post.html so that I can read the value of id in the URL parameter? Do I need to create a new angularJS app in post.html?
edit:
I've changed the read more link to <a href="post/{{post.sys.id}}"> and i am trying to set up the following route:
app.config(function($routeProvider){
$routeProvider
.when('/post/:postid',{
templateUrl: '/post.html',
controller: 'postCtrl'
})
});
However, clicking the "read more" link doesn't load up post.html, but instead a page that says File not found: /post/2B1K9K2DHqsYaGYcms2YeW. The route doesn't seem to be getting properly set up, since post.html isn't getting loaded.
This isn't all that hard to do, but you need to have routing set up on your app. You can create this functionality in your existing app, or separate it into a new one, it's up to you. Here are the relevant things you'll need to include in your code:
In your app include ngRoute as a dependency:
var myApp = angular.module('myApp', ['ngRoute']);
Also include routing config for your app:
myApp.config(function($routeProvider){
$routeProvider
.when('/someroute', {
templateUrl: 'someFolder/withSomeFile.html'
}
.when('/someroutewithparamters/:aftercolonisparameter', {
templateUrl: 'someFolder/post.html'
}
});
You can include a default route as well, but it's not necessary if you'd rather not. Be sure to include angular-route.js in your index.html for this to work.
Now in your controller you can simply do something like:
myApp.controller('postCtrl', function($routeParams, $scope, postFactory){
$scope.post = postFactory.functionToLoadPost($routeParams.aftercolonisparameter);
});
Obviously this will be different for your implementation based on how everything is set up, and you'll probably want to pick better names for your elements than I did, but those are the things you'll need in place to make this work. It's actually pretty straightforward.

converting Jquery to angular or making Jquery work in angular

I am new to angular and we are converting a set of screens based on jsp to angular. Initially we have written lot of code in Jquery. Converting them to angular is tedious task and thought of trying to see if we can make jquery work with angular. Here is teh code snippet that i am trying to make it work while it in Jquery.
$(document).ready(function() {
$("#ClickTask2").click(function() {
$(".ClickTask1").hide();
$(".ClickTask2").show();
});
});
Above is the piece of code I have in JQuery and i tried to make it work.
angular.element(document).ready(function() {
$("#ClickTask2").click(function() {
$(".ClickTask1").hide();
$(".ClickTask2").show();
});
});
Can anyone tell me how i could make it work with minimal changes to the above one and rest of the jqueries?
You can convert many jquery features over to Angular by simply changing the $() method to angular.element() e.g.
$('#output').html('<h1>Title</h1>');
You could convert this to:
angular.element('#output').html('<h1>Title</h1>');
However not all function work, and some are renamed e.g.
$("#output").click(function() { console.log('Hi'); });
Would need to be changed to:
angular.element('#output').on('click', function() { console.log('Hi'); });
You can find a full list of the supported functions here:
https://docs.angularjs.org/api/ng/function/angular.element
like said Luis Masuelli on the comments read the basis of Angular. a quick lesson
app.js
function TaskCtrl($scope) {
$scope.selectedTask = null;
$scope.tasks = [/* ... */];
$scope.onClickTask = function(task) {
$scope.selectedTask = task;
}
$scope.isSelected = function (task) {
return task === $scope.seletectedTask;
}
}
$scope it is a special variable, it is injected by Angular to controllers and serves to communicate the controller with the view among other things. A controller can be any function and the name does not matter.
main HTML
<ul data-ng-controller="TaskCtrl">
<li data-ng-repeat="task in tasks" data-ng-click="onClickTask(task)">
{{task.title}}
<div data-ng-show="isSelected(task)">{{task.description}}</div>
</li>
</ul>
data-ng-controller tells to Angular "this is the controller" for this tag and her children. The other directives are pretty explanatory, but the documentation you left it more clearly.
Of course I am assuming that your tasks has the following structure:
{
title: "...",
description: "..."
}
in your html you need include the angular.js, the previous js and a directive to tell angular that this is a application
<!DOCTYPE html>
<html>
<head></head>
<body data-ng-app>
<!-- main HTML -->
<script src="angular.js"><script/>
<script src="app.js"><script/>
</body>
</html>
the data- prefix on each directive is not necessary but as angular "extend" HTML and these are not native attributes, I use them to place custom attributes as "ng-repeat", "ng-controller", "ng-app" etc. They are called directives
Remember, with Angular you need not manipulate the DOM directly as is done with jQuery, except for some special exceptions

Using routeProvider when not on site root

Sorry if I'm missing something obvious, very new to Angular.
I'm running an application on this page: //hosted.demo.ca/md/SitePages/Home.aspx
I'm trying to set up the routing on the application but the page is just rendering blank with no errors in console.
routeProvider:
var spApp = angular.module('spApp', [])
.config(function($routeProvider){
$routeProvider.when('/userView',
{
templateUrl: 'partials/userView.html',
controller: 'userCtrl'
})
});
and my html like such:
<div id="mdContainer" ng-cloak>
<!-- Navigation -->
<div id='mdSidebar'>
<ul>
<li id="menuHome"><a href='#'><span>Home</span></a></li>
<li id="menuUsers"><a href='#/userView'><span>Users</span></a></li>
<li id="menuGroups"><a href='#'><span>Groups</span></a></li>
<li id="menuSites"><a href='#'><span>Sites</span></a></li>
<li id="menuReports"><a href='#'><span>Reports</span></a></li>
</ul>
</div>
<!-- Main view -->
<ng-view></ng-view>
</div>
Have you added the route module? Please try using something like:
var spApp = angular.module('spApp', ['ngRoute'])
See here for more information about this. In newer versions of Angular the route functions were moved to a separate module.
Also I can tell you from personal experience that it is very easy to forget to add the angular-route.js file into your html file using something like:
<script src="path/to/angular-route.js">
If you use bower you can easily set this up with:
bower install angular-route

Dynamically load modules angular

I'm looking for a way to load a module (js, css and html) with just one directive anytime during the app life.
<my-module id="contacts"></my-module>
And the template of this directive generates
<my-module id="contacts">
<link type="stylesheet" href="modules/contacts/contacts.css">
<script type="text/javascript" src="modules/contacts/contacts.js"></script>
<ng-include src="modules/contacts/contacts.html"></ng-include>
</my-module>
And the .js file creates a new angular module
// modules/contacts/contacts.js
angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });
And the '.html' uses a controller in this module
// modules/contacts/contacts.html
<ul ng-controller="ContactsCtrl">
<li ng-repeat="contact in contacts">{{ contact.name }}</li>
</ul>
It wont work because the page's module <html ng-app="my-app"> does not depends on my-contacts module. So I would like every module to inject itself as a my-app dependency.
I've found every module (object returned by angular.module) contains a requires array with it's dependencies. I've injected my-contacts into that array and this works:
// modules/contacts/contacts.js
angular.module('my-app').requires.push('my-contacts');
angular.module('my-contacts', [])
.controller(ContactsCtrl, function($scope) { ... });
But I can't find this property on the documentation. Is it standard or it can change anytime? anyone knows?
Update
To be clear, this is not to load a single module with a single component, this is meant to load a entire application, imagine it like a launcher (like MacOS dockbar or Ubuntu's unity sidebar) with dynamically added icons and when one of this icons are clicked it should run the module. But I don't know at the webpage start which apps this launcher should be able to launch and I need to add more applications dynamically. As each app can has it's own directives and services I use angular modules as apps.
<body ng-app="my-app">
<ul>
<li ng-repeat="module in modules">
<button ng-click="selectedApp = module.id">{{ module.name }}</button>
</li>
</ul>
<my-module id="{{ selectedApp }}"></my-module>
</body>
I'm not sure you're trying to abstract the code so much.
What you should be able to do:
Make a module
Put a directive in the module with your contacts list
Inject the module into your page. And use the contact list.
Dependencies are usually the second argument of a module definition. i.e:
angular.module('my-app', ['my-contacts']);
Is this what you were referring to? The dependencies and how to inject them correctly?

Categories

Resources