In Angular1.5+, how to import and use the independent component? - angularjs

Now, I write an Angular1.5+ component in one folder.
The component in an independent folder.
My issue is how to use this component in different HTML. In other words, I want to find a method to import this component in more than two HTML files.
The cellComponent.js is like this:
function courseCellComponentFun() {
var ctrl = this;
}
angular.module(app_name).component('courseCell', {
templateUrl: '../cellComponent.html',
controller:courseCellComponentFun,
bindings:{
cellData:'='
}
})
The cellComponent.html is like this:
<div class="course_cell">
<div class="img_box">
<div ng-bind="$ctrl.cellData.name"></div>
</div>
</div>
The index.html like this:
<body ng-app="app" ng-controller="controller">
<ul>
<li ng-repeat="item in array1">
<course-cell cell-data="item"></course-cell>
</li>
</ul>
</body>
<script src="angular.js"></script>
<script>
var app = angular.module('app',[]);
app.controller('controller', function ($scope) {
$scope.array1 = [
{name:'cell1'},
{name:'cell2'},
{name:'cell3'},
]
});
</script>
How to import the component in the index.hmtl? My index.html does not work now. I can't see the text.

Well, If you're not using Typescript or Babel or the new ES6 standard for importing and exporting modules, I'm affraid you have to add the reference of your component.js file, as simple as <script src="cellComponent.js"></script>in the index.html
index.html
<html>
<head>
<script src="angular.js"></script>
<script src="cellComponent.js"></script>
<script src="appModule.js"></script>
</head>
<body ng-app="app" ng-controller="controller">
<ul>
<li ng-repeat="item in array1">
<course-cell cell-data="item"></course-cell>
</li>
</ul>
</body>
</html>
appModule.js
var app = angular.module('app',[]);
app.controller('controller', function ($scope) {
$scope.array1 = [
{name:'cell1'},
{name:'cell2'},
{name:'cell3'},
];
})
.component("courseCell", componentOpts); // componentOpts comes from the componentOpts.js script
cellComponent.html
<div class="course_cell">
<div class="img_box">
<div ng-bind="$ctrl.cellData.name"></div>
</div>
</div>
cellComponent.js
function courseCellComponent() {
var ctrl = this;
}
var componentOpts = {
templateUrl: './cellComponent.html',
controller: courseCellComponent,
controllerAs: "$ctrl",
bindings: {
cellData:'=',
}
};
See this plunkr

Related

Angular loading Controllers and Services

I am using Angularjs for my application.I am having one common page which has header and footer which i am making common for all pages.Thats y i am placing it in one common html.Only contents code i am placing in other html pages.
As i am using one common page i am loading all controllers and all Services that i am using in the application.
Here is my commonpage.html
<!DOCTYPE html>
<html lang="en" data-ng-app="adminApp">
<head>
</head>
<body>
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="resources/angular/controller/admin/AdminExamController.js">
</script>
<script src="resources/angular/service/admin/AdminExamService.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
The doubt i am having is,is it necessary to place all controllers and services like i am doing because i am facing performance issue even though i am connected to strong internet it loads very slow.As i am placing all in one page it is loading all controllers and services everytime.If i place controllers in their respective html then i am getting error like ExamController.js or any .js Controller not defined.Is there any other way that i can load all controllers and services so that i can increase the performance of the application?
I think this is what your looking for
app.js
/* Module Creation */
var app = angular.module ('adminApp', ['ngRoute']);
app.config(['$routeProvider', '$controllerProvider', function($routeProvider, $controllerProvider){
/*Creating a more synthesized form of service of $ controllerProvider.register*/
app.registerCtrl = $controllerProvider.register;
function loadScript(path) {
var result = $.Deferred(),
script = document.createElement("script");
script.async = "async";
script.type = "text/javascript";
script.src = path;
script.onload = script.onreadystatechange = function (_, isAbort) {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (isAbort)
result.reject();
else
result.resolve();
}
};
script.onerror = function () { result.reject(); };
document.querySelector("head").appendChild(script);
return result.promise();
}
function loader(arrayName){
return {
load: function($q){
var deferred = $q.defer(),
map = arrayName.map(function(name) {
return loadScript(name+".js");
});
$q.all(map).then(function(r){
deferred.resolve();
});
return deferred.promise;
}
};
}
$routeProvider
.when('/view2', {
templateUrl: 'view2.html',
resolve: loader(['Controller2'])
})
.when('/bar',{
templateUrl: 'view1.html',
resolve: loader(['Controller1'])
})
.otherwise({
redirectTo: document.location.pathname
});
}]);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js"></script>
</head>
<body ng-app="adminApp">
<!--Here is header code-->
<div class="LeftMenu">
<ul class="navbar">
<a href="#!/admindashboardhome" title="Dashboard"><li>
<span>Dashboard</span></li>
</a>
<a href="#!/examinationhalltickets" title="Declaration"><li>
<span>Examination Form</span></li>
</a>
<a href="#!/collegedetails" title="Declaration"><li>College
Details</li>
</a>
</ul>
</div>
<!--followed by footer code-->
<div data-ng-view> <!--ng-view-->
</div>
<!--Here i am loading all controllers and services related to application-->
<script
src="app.js">
</script>
<!-- And many more in same fashion-->
</body>
</html>
Controller 1.js
(function(val){
'use strict';
angular.module('Controller1App', [])
.controller('Controller1', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Controller 2.js
(function(val){
'use strict';
angular.module('Controller2App', [])
.controller('Controller2', ['$http','$rootScope','$scope','$window', function($http,$rootScope, $scope, $window){
//Your code goes here
}])
})(this);
Refer https://plnkr.co/edit/cgkgG5PCwJBVOhQ1KDW2?p=preview

Retrieving data in AngularJS "net::ERR_CONNECTION_REFUSED"

Im working in laravel and i start to implement angular to my frontend.
This is the route:
Route::get('test', 'WorkController#inicio');
My controller function:
public function inicio()
{
$works = new Work;
$works = Work::Paginate(10);
return view('test', compact('works'));
}
And the view where i what to display the database information.
<head>
<title>test</title>
<link href="/css/lib.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js">
</script>
</head>
<body>
<h1>test</h1>
<h2>test</h2>
<div ng-app="myApp" ng-controller="myController as controller">
<ul>
<li ng-repeat="datos in data">
<a class="floating-box">#{{datos.client}}</a>
</li>
</ul>
</div>
<hr/>
</body>
<script type="text/javascript">
var app = angular.module("myApp", []);
app.controller("myController", function($scope, $http) {
$scope.data = [];
$scope.buscador = '';
$http.get("<?=env('APP_URL')?>" + '/test').then(function(datos) {
console.log(datos.data.data);
$scope.data = datos.data.data;
console.log($scope.data);
})
});
</script>
But then i get this in console:
GET http://localhost/test net::ERR_CONNECTION_REFUSED.
and the information isnt in the view.

Passing Data between state Providers in angular

Im looking to pass data between 2 controllers in Angular, Below is code i started
There are 2 views one with input field and other with a link.
when i click on link in the second view i should be able to set a state and state data should be populated in input field in first field.
I tried several approaches but im missing something.
Can someone help me here
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider','$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <input type="text" ng-model={{input-text}}>' ,
data:""
},
viewBookv = {
name: 'viewBookv',
url: '/viewBook',
template: '<h2>View A book</h2><span class="glyphicon glyphicon-edit">Edit</span> ' ,
};
$stateProvider.state(addBook, "controller: editUserCtrl");
$stateProvider.state(viewBookv, "controller: editUserCtrl");
}])
myApp.controller('editUserCtrl', function($scope, $stateParams) {
$scope.paramOne = $stateParams.data;
$scope.edit = function () {
event.preventDefault();
$state.go("addBook");
}
})
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBookv");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
Typically in angular the way to share state between controllers is using a service. So the way it's usually set up is to setup a service then import that service into the relevant controllers, and that data gets shared between them. I've modified your example above to follow this pattern(I'm not quite sure what you were trying to do)
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Hello AngularJS</title>
<script data-require="angular.js#1.2.10" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.min.js"></script>
<script src="http://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', ['ui.router']);
myApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider,$urlRouterProvider) {
var addBook = {
name: 'addBook',
url: '/addBook',
template: '<h2>Add A book</h2> Data from View <button ng-click="updateBook()">Update</button> <input type="text" ng-model="inputText">' ,
controller: "addBookCtrl",
data:""
},
viewBookv = {
name: 'viewBooks',
url: '/viewBook',
template: '<h2>View A book</h2><div ng-repeat="book in bookList">{{book}}</div>',
controller: "viewBookCtrl",
};
$stateProvider.state('addBook', addBook);
$stateProvider.state('viewBooks', viewBookv);
}])
myApp.controller('addBookCtrl', function($scope, bookService) {
$scope.updateBook = function(){
console.log( $scope.inputText)
bookService.books.push($scope.inputText);
}
})
myApp.controller('viewBookCtrl', function($scope, bookService) {
$scope.bookList = bookService.books
})
myApp.factory('bookService', function() {
var bookService = {};
bookService.books = [];
return bookService;
});
myApp.controller('mainController',function($scope, $rootScope, $state,$window){
$scope.addBook=function(){
$state.go("addBook");
};
$scope.viewbookls= function(){
$state.go("viewBooks");
};
})
</script>
</head>
<body>
<div class="container">
<div class="col">
<div class="col-md-3" ng-controller="mainController">
<ul class="nav">
<li> View Book </li>
<li> Add Book </li>
</ul>
</div>
<div class="col-md-9">
<div ui-view></div>
</div>
</div>
</div>
</body>
</html>
What this example does, is in the text box for add book, you type in the name (then click update), this appends it to an array so every time you do it you'll get a new element on that array. From there head over to the view books page, and you'll see all the different things you typed in.

Angular view not loading

Im not sure where to place the partials folder holding the html views! I have placed it at the app root folder, in views and in public. Also tried removing the first trailing slash of the templateUrl but nothing. I also have tried(as view loading container):
<div ng-view></div>
<ng-view></ng-view>
<div data-ng-view></div>
<div ng-view=""></div>
<div ng-view="demoApp"></div>
This is just a learning example holding a module with 2 controllers and 2 views.
Here is the SPA(this page renders as rout '/' of a dancer(perl) project):
<!DOCTYPE html>
<html ng-app="demoApp">
<head>
<title><% title %></title>
<link rel="stylesheet" href="/customised_bootstrap/css/bootstrap.css">
<script src="/bower_components/underscore/underscore.js"></script>
<script src="/bower_components/backbone/backbone.js"></script>
<script src="/bower_components/angular/angular.js"></script>
<script src="/bower_components/angular-resource/angular-resource.js"></script>
<script src="/bower_components/angular-route/angular-route.js"></script>
<script src="/bower_components/ng-tasty/ng-tasty-tpls.js"></script>
<script>
//define a module
var demoApp = angular.module('demoApp', ['ngRoute']);
//define routes for our module(each route will have its set of views and controllers)
demoApp.config =(function ($routeProvider) {
$routeProvider
.when('/',
{
controller: 'simpleController1',
templateUrl: '/partials/testAlexView1.html'
})
.when('/testAlexView1',
{
controller: 'simpleController2',
templateUrl: '/partials/testAlexView1.html'
})
.when('/testAlexView2',
{
controller: 'simpleController2',
templateUrl: '/partials/testAlexView2.html'
})
.otherwise({redirectTo: '/partials/testAlexView1.html'});
});
//define a controller within our module 'demoApp'
demoApp.controller('simpleController1', function ($scope) {
$scope.customers = [
{name:'Boris', age:'18'},
{name:'Claudia', age:'28'},
{name:'Carlos', age:'39'},
{name:'Ben', age:'25'}
];
//var stuff ={};
});
demoApp.controller('simpleController2', function ($scope) {
$scope.customers = [
{name:'Alex', age:'18'},
{name:'Albert', age:'28'},
{name:'Anthony', age:'39'},
{name:'Loren', age:'25'}
];
});
</script>
</head>
<body>
<div>
<p>Main page of SPA test</p>
<div ng-view></div>
</div>
</body>
</html>
Here are the two identical views:
testAlexView1.html(testAlexView2.html is the same):
<div>
<input type="text" data-ng-model="name" /> {{ name }}
<br />
<ul>
<li data-ng-repeat="customer in customers | filter:name | orderBy:'age'">
{{customer.name}} - {{customer.age}}
</li>
</ul>
</div>
In the browser inspector, within the div where the view should load, all that appears is(both at root or root#/view.html):
<!-- ngView: -->
Batarang dosn't detect scopes nor modules neither. Thanks for any help!
There appears to be a typo in your config here:
demoApp.config =(function ($routeProvider) {
Instead try:
demoApp.config(function ($routeProvider) {

Basic Angularjs routing failing to get template

I'm new to Angular and I want to setup very basic routing. My cart.html has the text: "Hello Cart" and by going to #/Step I want to change this to "Hello World".
(My console is not giving me any error messages)
I have: someurl.com/page and when I change it to: someurl.com/page#/Step nothing happens.
This is the HTML
<div class="row" ng-app="ecom">
<div class="large-12 columns" ng-include="'cart.html'">
<div ng-view></div>
</div>
</div>
This is the JS
var ecom = angular.module('ecom', ['ngRoute', 'ngResource']);
ecom.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Step', {
template: 'hello world'
});
});
Having the ng-include on the parent div is messing it up.
One way to solve this is to add another route on "/" and set that routes templateUrl to "cart.html"
(function() {
var ecom = angular.module('ecom', ['ngRoute']);
ecom.config(function($routeProvider) {
$routeProvider
.when("/", {
template: "hello cart", //remove this line to use cart.html
templateUrl: "cart.html"
})
.when("/step", {
template: "hello world"
});
});
})();
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.3.0" src="//code.angularjs.org/1.3.0/angular.js"></script>
<script data-require="angular-route#*" data-semver="1.2.20" src="https://code.angularjs.org/1.2.20/angular-route.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="ecom">
To Step
<div>
<div ng-view>
</div>
</div>
</div>
</body>
</html>
Also: here is a plunk

Resources