Could you please let me know what is wrong with my code? I get the initial HTML page, but when I click on "Open", nothing happens. Not even the console logs an error, or any other change.
app.js
var app = angular.module('carApp', ['ui.bootstrap']);
ctrl.js
app.controller('carCtrl', function($scope, $http, $uibModal) {
$http.get('jobs.json').success(function(data) {
$scope.data = data;
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller : modalContentCtrl,
resolve: {
items: function() {
return $scope.data;
}
}
})
}
});
});
var modalContentCtrl = function ($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
};
JSON:
{
"specs":[
{
"job-title":"TITLE",
"job-apply":"applink",
"job-body":"JOB BODY"
}
]
}
HTML:
<div class="car-up">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="item in data">{{item}}</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
I'm new to AngularJS, but I have linked the app.js and ctrl.js... thanks.
EDIT: after I've placed ng-controller="carCtrl" in the html file, I receive this error:
Error: [$injector:unpr]
http://errors.angularjs.org/1.5.7/$injector/unpr?p0=%24modalInstanceProvider%20%3C-%20%24modalInstance
O/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:6:412
db/n.$injector<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:84
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
db/V<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:43:144
d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:40:344
e#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:78
h/<.invoke#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:41:163
gf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:89:397
resolveSuccess#https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.2.0/ui-bootstrap-tpls.js:4422:34
e/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:130:409
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:103
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:142:165
vf/this.$gethttps://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:145:399
Lc[b]https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:274:444
Sf#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:37:31
Rf/d#https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js:36:486
Please find working demo
angular.module('carApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
var app = angular.module('carApp');
app.controller('carCtrl', function($scope, $http, $uibModal) {
//$http.get('jobs.json').success(function(data) {//Uncomment
//$scope.data = data; Uncomment
//Remove below line from code when you are using this in your project
$scope.data = {
"specs": [{
"job-title": "TITLE",
"job-apply": "applink",
"job-body": "JOB BODY"
}]
}
$scope.open = function() {
var modalContent = $uibModal.open({
templateUrl: 'careersTpl.html',
controller: 'ModalInstanceCtrl',
controllerAs: '$ctrl',
resolve: {
items: function() {
return $scope.data;
}
}
})
}
//});//Uncomment
});
app.controller('ModalInstanceCtrl', function($uibModalInstance, items, $scope) {
$scope.data = items;
console.log($scope.data);
$scope.selected = {
item: $scope.data.specs
};
});
<!doctype html>
<html ng-app="carApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-animate.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-sanitize.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.3.0.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="carCtrl" class="modal-demo">
<script type="text/ng-template" id="careersTpl.html">
<div class="modal-header">
<h3>Lorem Ipsum</h3>
</div>
<div class="modal-body">
<p ng-repeat="(k,v) in data.specs">
<span>Title: {{v["job-title"]}}<br/> </span>
<span>Link: {{v["job-apply"]}}<br/> </span>
<span>Body: {{v["job-body"]}}<br/> </span>
</p>
</div>
</script>
<button class="btn" ng-click="open()">Open</button>
</div>
</body>
</html>
Try defining the controller like this outside,
app.controller('modalContentCtrl ', function($scope, $modalInstance, data) {
$scope.data = data;
$scope.selected = {
item: $scope.data.specs
};
}
Related
I am very new to js overall so please be patient with me.
I need to make a simple task which is stated in the topic. I have done some research and tried to make using ui.router but since I am not very good with coding something went wrong.
I want that this information from url would be displayed inside the modal dialogue http://prntscr.com/ashi5e
So here is the code:
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
};
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
<!doctype html>
<html ng-app="plunker">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="js/example.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>Log</h3>
</div>
<div class="modal-body">
Content
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Close</button>
</div>
</script>
<button class="btn" ng-click="open()">Log</button>
</div>
</body>
</html>
You need to get the data (eg. with a service) and put it into $scope.items. In your modal do the same: get items and bind it to your scope. That's all
angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log, $http) {
/* Get data here with a service or smth */
$scope.items = '';
$scope.open = function () {
$http.get("YOUR_URL")
.then(function(response) {
$scope.items = response.data
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
});
};
};
var ModalInstanceCtrl = function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
<!doctype html>
<html ng-app="plunker">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
<script src="js/example.js"></script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>Log</h3>
</div>
<div class="modal-body">
{{items}}
</div>
<div class="modal-footer">
<button class="btn btn-warning" ng-click="cancel()">Close</button>
</div>
</script>
<button class="btn" ng-click="open()">Log</button>
</div>
</body>
</html>
You didn't registered modalDemoCtrl and ModalInstanceCtrl at first you need to register both controller like: myApp.controller('modalDemoCtrl', ModalDemoCtrl); where myApp is angular module like: var myApp = angular.module('plunker', ['ui.bootstrap']);.
you can use a service to get data from an url by using$http and that service inject in your modalInstance controller. in my example create dataService and a function named getData and called this function from modalInstance controller. like: dataService.getData().then(.. and use then function to get response. and store response data in to $scope.infos variable so you can use this $scope.infos in your modal.
var myApp = angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal, $log) {
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
resolve: {
items: function () {
return $scope.items;
}
}
});
};
};
myApp.controller('modalDemoCtrl', ModalDemoCtrl);
myApp.factory('dataService', function($http) {
return {
getData: function() {
return $http.get('http://prnt.sc/ashi5e');
}
};
});
var ModalInstanceCtrl = function ($scope, $modalInstance, items, dataService) {
dataService.getData().then(function(response) {
$scope.infos = response.data;
});
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
myApp.controller('ModalInstanceCtrl', ModalInstanceCtrl);
Referring to the code given below, I would like to be able to load viewTeam URL into ng-view from the showTeam() function. How can I do this?
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.min.js"></script>
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
var showTeam = function(id) {
}
});
teamApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
teamApp.controller('AddTeamController', function($scope) {
});
teamApp.controller('ViewTeamController', function($scope, $routeParams) {
});
</script>
</head>
<body>
<div ng-app = "teamApp" ng-controller="teamController">
<button ng-click="newTeam()">new</button>
<div ng-repeat="team in teams" >
Name: {{team.name}}
<br />
Description: {{team.description}}
<br />
<button ng-click="showTeam(team.id)">show</button>
</div>
<div ng-view></div>
<script type = "text/ng-template" id = "addTeam.htm">
<h2> Add Team </h2>
To be implemented later.
</script>
<script type = "text/ng-template" id = "viewTeam.htm">
Name: {{team.name}}
Description: {{team.description}}
</script>
</div>
</body>
</html>
You need to change your $routeprovider for viewTeam to expect an id parameter. Then get that id in the viewTeamController using routeparams. Here is how you do it. Just follow the pattern in the script below:
<script>
var teamApp = angular.module("teamApp", ['ngRoute']);
teamApp.controller('teamController', function($scope, $http,$location) {
$http
.get('/teams')
.success(function(response) {
$scope.teams = response;
}
);
var showTeam = function(id) {
$location.url("#/viewTeam/" + id);//there are other means as well.
}
});
teamApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addTeam', {
templateUrl: 'addTeam.htm',
controller: 'AddTeamController'
}).
when('/viewTeam/:id', {
templateUrl: 'viewTeam.htm',
controller: 'ViewTeamController'
}).
otherwise({
redirectTo: '/addTeam'
});
}]);
teamApp.controller('AddTeamController', function($scope) {
});
teamApp.controller('ViewTeamController', function($scope, $routeParams) {
alert($routeParams.id);//you get the route params here.
});
</script>
When navigating from view:
<a href="#viewTeam/45">
In your case:
<a href="#viewTeam/{{team.id}}"> //to navigate from view.
In your teamController do this -
var showTeam = function(id) {
$location.path('/viewTeam.htm').search({'id': id});
}
In ViewTeamController you can get id like this
//Get id from url params
$location.search('id');
you can use $location to change the path
$scope.showTeam = function(view){
$location.path("/viewTeam"); // path not hash
}
var myApp = angular.module("MyApp", ['ngRoute']);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/cart.php',
controller: 'ctrl',
resolve: {
categories: function(cartService){
console.log('inside resolve categories')
return cartService.getCategories();
}
}
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrl', function (categories, $scope) {
$scope.items = categories;
});
myApp.service("cartService", function ($http, $q) {
this.getCategories = function () {
var deferred = $q.defer();
$http.get('js/categories.js')
.then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
}
});
myApp.run(['$rootScope',function($rootScope){
$rootScope.stateIsLoading = false;
$rootScope.$on('$routeChangeStart', function(e, current, pre) {
$rootScope.stateIsLoading = true;
var fullRoute = current.$$route.originalPath;
if(fullRoute == '/')
{
console.log('load categoreis and products')
}
});
$rootScope.$on('$routeChangeSuccess', function() {
$rootScope.stateIsLoading = false;
console.log('route changed');
});
$rootScope.$on('$routeChangeError', function() {
//catch error
});
}]);
I have placed the ng-app and ng-controller directives at the top of the HTML
<html lang="en" ng-app="MyApp" ng-controller="ctrl">
But when I run the HTML I get the following error
Error: [$injector:unpr] Unknown provider: categoriesProvider <-
categories <- ctrl
How can I fix this ?
Edit: If I remove ng-controller="ctrl" from the HTML, then no errors
You got that error just because, you are using the same controller for both index.php and 'partials/cart.php'
Create a separate controller for 'partials/cart.php' to resolve this
problem
Code Snippet:
// Code goes here
var app = angular.module('app', ['ngRoute']);
app.controller('indexCtrl', function($scope) {
$scope.title = 'Header';
});
app.config(function($routeProvider) {
$routeProvider.when('/', {
template: "<ul><li ng-repeat='item in items'>{{item}}</li></ul>",
controller: 'categoryCtrl',
resolve: {
categories: function(cartService){
return cartService.getCategories();
}
}
});
});
app.controller('categoryCtrl', function (categories, $scope) {
$scope.items = categories;
});
app.service("cartService", function() {
this.getCategories = function() {
return ['A', 'B', 'C'];
};
});
<html ng-app="app">
<head>
<script data-require="angular.js#1.4.9" data-semver="1.4.9" src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script data-require="angular-route#1.4.2" data-semver="1.4.2" src="https://code.angularjs.org/1.4.2/angular-route.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="indexCtrl">
<h1>{{title}}</h1>
<div ng-view></div>
</body>
</html>
you have to define the categories service/factory which is injected in your controller 'ctrl'.
In web application there are a lot of modal template (angular foundation modal). When the modal is opened, we must give controller that are created in the page javascript file. but this controller are generally written inline. I want to get these controller as external or dynamically load.
It is like :
var modalInstance = $modal.open({ templateUrl: 'myModalContent.html',
controller: 'modal-controller.js' })
can it be done? if so, how can I do that this,
thank your helps
Would you try this?
angular.module('foundationDemoApp', ['mm.foundation']);
angular.module('foundationDemoApp').controller('ModalDemoCtrl', function ($scope, $modal, $log) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $modal service used above.
angular.module('foundationDemoApp').controller('ModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
<!doctype html>
<html ng-app="foundationDemoApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.js"></script>
<script src="//pineconellc.github.io/angular-foundation/mm-foundation-tpls-0.5.1.js"></script>
<script src="example.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/foundation/5.2.0/css/foundation.css" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="small-12.columns">
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<h3>I'm a modal!</h3>
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
<p>Selected: <b>{{ selected.item }}</b></p>
<button class="button" ng-click="ok()">OK</button>
<a class="close-reveal-modal" ng-click="cancel()">×</a>
</script>
<button class="button" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
</div>
</div>
use oclazyload
function nameOpen(name){
$ocLazyLoad.load('modal/name.ctrl.js').then(function(){
var modalInstance = $modal.open({
templateUrl: 'modal/name.html',
controller: 'nameCtrl',
controllerAs: 'vm',
resolve: {
phones: function () {
return name;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
//$log.info('Modal dismissed at: ' + new Date());
});
});
}
I am new to angular. I have tried creating an application and all was going well until I decided to create a custom directive.
My html looks like this:
<body ng-app="sapphireApp">
<div class="off-canvas-wrap" data-offcanvas>
<div class="inner-wrap">
<nav class="tab-bar">
<section class="middle tab-bar-section">
<h1 class="title">Sapphire</h1>
</section>
<section class="right-small">
<a class="right-off-canvas-toggle menu-icon" href="#"><span></span></a>
</section>
</nav>
<aside class="right-off-canvas-menu" ng-controller="TopController as topController">
<ul class="off-canvas-list">
<li><label>Users</label></li>
<li ng-hide="topController.userService.isLoggedIn">Login</li>
<li ng-show="topController.userService.isLoggedIn">Logout</li>
</ul>
</aside>
<section class="main-section" ng-view></section>
<a class="exit-off-canvas"></a>
</div>
</div>
<script src="scripts/angular.min.js"></script>
<script src="scripts/mm-foundation/mm-foundation-0.5.1.min.js"></script>
<script src="scripts/angular-cookies.min.js"></script>
<script src="scripts/angular-route.min.js"></script>
<script src="scripts/angular-touch.min.js"></script>
<script src="scripts/app/app.js"></script>
<script src="scripts/app/controllers.js"></script>
<script src="scripts/app/services.js"></script>
<script src="scripts/app/directives.js"></script>
</body>
and my four angularJS files look like this respectively:
app.js
angular.module('sapphireApp', ['ngRoute', 'ngCookies', 'ngTouch', 'mm.foundation'])
.config(function ($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'views/home/index.html'
})
.when('/login', {
templateUrl: 'views/account/login.html'
})
$routeProvider.otherwise({
redirectTo: '/'
});
});
controllers.js
angular.module('sapphireApp')
.controller('TopController', ['UserService',
function (UserService) {
var self = this;
self.userService = UserService;
// Check if the user is logged in when the application
// loads
// User Service will automatically update isLoggedIn
// after this call finishes
UserService.session();
}
])
.controller('HomeController',
function () {
var self = this;
}
)
.controller('LoginController', ['UserService', '$location',
function (UserService, $location) {
var self = this;
self.user = { username: '', password: '' };
self.login = function () {
UserService.login(self.user).then(function (success) {
$location.path('/');
}, function (error) {
self.errorMessage = error.data.msg;
})
};
}
]);
services.js
angular.module('sapphireApp')
.factory('UserService', ['$http', '$cookieStore', function ($http, $cookieStore) {
var service = {
isLoggedIn: false,
session: function () {
var user = $cookieStore.get('user');
if (user)
service.isLoggedIn = true;
return user;
},
login: function (user) {
return $http.post('/api/account/login', user)
.then(function (response) {
service.isLoggedIn = true;
$cookieStore.put('user', response);
return response;
});
}
};
return service;
}]);
directives.js
angular.module('sapphireApp')
.directive('square', function () {
return {
restrict: 'E',
template: '<div class="square"><h1>Show something else</h1></div>',
link: function () {
alert("this is working");
}
};
});
The login view works fine, but the home view doesn't. It looks like this:
<div class="row" ng-controller="HomeController as homeController">
<div class="small-2 columns">
<sqaure>
<h1>This is the square</h1>
</sqaure>
</div>
</div>
Now, because I have created the directive square and set it to be an element, I would expect an output like this:
<sqaure>
<div class="square">
<h1>Show something else</h1>
</div>
</sqaure>
and I would also expect there to be an alert. But I get nothing. No errors and the Html stays unmodified.
Can anyone tell me why? I assume because I am getting no errors, it is just a misunderstanding on my part.
You have a typo in the directive:
<sqaure> //typo here
<h1>This is the square</h1>
</sqaure> //typo here
Change sqaure to square.