Angular controllers and directives getting values from controller into directive - javascript

I have a directive in my angular website that builds a page header, in that page header I am wanting to show the user's first and last name. I am wrapping my entire application in a MainController. My rendered HTML looks like this,
<html ng-app="app" ng-controller="MainController as main" class="fa-events-icons-failed ng-scope">
<head>
<style type="text/css">#charset "UTF-8";[ng\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>
<meta charset="utf-8">
<title ng-bind="main.windowTitle" class="ng-binding">App School Management</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="dist/css/generic.css">
<link rel="stylesheet" type="text/css" href="dist/css/styles.min.css">
<script src="https://use.fontawesome.com/2a6c262d81.js"></script><script src="https://cdn.fontawesome.com:443/js/stats.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/2a6c262d81.css" media="all">
</head>
<body cz-shortcut-listen="true">
<div id="page-wrapper">
<div id="page-header" class="bg-gradient-9 ng-isolate-scope" header="" user="userModel">
<div id="mobile-navigation">
<button id="nav-toggle" class="collapsed" data-toggle="collapse" data-target="#page-sidebar"><span></span></button>
</div>
<div id="header-logo" class="logo-bg">
<a ui-sref="dashboard.home" class="branding" title="Schoozle">
App Logo
</a>
<a id="close-sidebar" href="#" title="Close sidebar">
<i class="fa fa-chevron-left" aria-hidden="true"></i>
</a>
</div>
<div id="header-nav-left">
<div class="user-account-btn dropdown">
<a href="#" title="My Account" class="user-profile clearfix" data-toggle="dropdown">
<img width="28" src="http://placehold.it/40x40" alt="Profile image">
<span ng-bind="$scope.user.first_name" class="ng-binding"></span>
<i class="fa fa-chevron-down" aria-hidden="true"></i>
</a>
</div>
</div>
<!-- #header-nav-left -->
<div id="header-nav-right">
<div class="dropdown" id="notifications-btn">
<a data-toggle="dropdown" href="#" title="">
<span class="small-badge bg-yellow"></span>
<i class="fa fa-bell" aria-hidden="true"></i>
</a>
<div class="dropdown-menu box-md float-right">
<!-- Notifications Dropdown -->
</div>
</div>
</div>
</div>
My non directive HTML looks like this,
<div header user="userModel"></div>
And my controller code, and directive code looks this,
app.directive('header', [function () {
return {
restrict: 'A', //This menas that it will be used as an attribute and NOT as an element. I don't like creating custom HTML elements
replace: true,
scope: {user: '='}, // This is one of the cool things :). Will be explained in post.
templateUrl: "/templates/partials/header.html",
controller: ['$scope', '$filter', function ($scope, $filter) {
// Your behaviour goes here :)
}]
}
}]);
app.controller('MainController', ['$scope', 'UserService', function($scope, UserService){
var self = this;
this.windowTitle = "App School Management";
this.loading = true;
this.user = {};
UserService.authenticatedUser()
.then(function(response){
self.loading = false;
self.userModel = response.message;
}, function(error) {
self.hasError = true;
self.errors = error.message;
});
}]);
How do I get my user object from the controller into the directive?

Since you are using MainController as main, add main to your directive:
<div header user="main.userModel"></div>
than user data will be available through your isolated scope two way binding within your 'templates/partials/header.html' as user object, something like user.firstName and user.lastName.
You can avoid using $scope by adding to your directive definition
controllerAs: 'ctrl';
bindToController: true;
than your user data will be available witin HTML as ctrl.user object

Related

How can I create a modal list of values using just bootstrap and angular with springboot as a backend?

I am trying to make a generic "List of Values", a searchable modal with a natural identifier and a description. I have managed to create an angularjs app that does this in SpringBoot but it is not callable as a modal.
I want to use nothing but angularjs, bootstrap and springboot mvc, I don't want to get into node as the backend.
I attempted to follow the instructions here:
https://www.uibootstrap.net/angular-ui-bootstrap/angular-bootstrap-modal-example-demo/
But they are incomplete, code fragments. I have tried to put it all together and have the following three files:
At this point I am getting
Error: [$injector:modulerr] Failed to instantiate module TestApp due to:
[$injector:modulerr] Failed to instantiate module ui.bootstrap due to:
[$injector:nomod] Module 'ui.bootstrap' 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.
I don't even know where this would get ui.bootstrap and the installation instructions for it say to use npm, I want to know what files are being used and place them in my springboot project. Npm and node are not in the architectural plans.
index.html:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Model</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<script src="./app.js"></script>
</head>
<body>
<div ng-app="TestApp">
<div class="well">
<button type="button" class="btn btn-primary" ng-click="openModal()">Click
to Open Modal Window!</button>
</div>
</div>
</body>
app.js:
var modalInstance = '';
var app = angular.module('TestApp', ['ui.bootstrap']);
app.controller('TestCtrl', function($scope, $http) {
function modalOpenCtrl($scope, payload){
console.log('fgfdfd');
$scope.datas = payload;
console.log($scope.datas);
$scope.closeModal = function(){
$scope.cancelModal();
}
}
$scope.openModal = function(task){
modalInstance = $uibModal.open({
animation: false,
templateUrl: './modal_window.html',
controller: 'modalOpenCtrl',
scope: $scope,
size: 'md',
backdrop: 'static',
resolve: {
payload: function () {
return {
msg_body : 'Hello! I am payload msg',
title : 'Hello! Title',
body_title : 'UiBootstrap.net'
};
}
}
});
}
function modalOpenCtrl($scope, payload){
console.log('fgfdfd');
$scope.datas = payload;
console.log($scope.datas);
$scope.closeModal = function(){
$scope.cancelModal();
}
}
})
modal_window.html:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Model</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<script>
src="./app.js"
</script>
</head>
<body>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close" ng-click="closeModal()">
<span aria-hidden="true">×</span>
</button>
<div class="modal-title">
<h4>{{datas.title}}</h4>
</div>
</div>
<div class="modal-body log-view">
<div class="clearfix">
<h2>{{datas.body_title}}</h2>
<div>{{datas.msg_body}}</div>
</div>
</div>
<div class="modal-footer model-grey-color">
<div class="clearfix">
<div>
<button class="btn btn-success" ng-click="closeModal()">
<i class="ace-icon fa fa-ok"></i> Ok
</button>
<button class="btn btn-danger" ng-click="closeModal()">
<i class="fa fa-close"></i> Close
</button>
</div>
</div>
</div>
</body>
It seems you haven't connected linking between controller and view
The error Failed to instantiate module ui.bootstrap due to: you are getting due to it's not loaded and you are trying to use this module.
Please check below for how to show modal using ui.bootstrap
First you need to create proper directory structure in order to load files when application run in browser.
Directory structure example:
Now let's jump to index.html
index.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Model</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div ng-app="TestApp" ng-controller="TestCtrl">
<div class="well">
<button type="button" class="btn btn-primary" ng-click="openModal('abc')">Click
to Open Modal Window!</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.3.3.js"></script>
<script src="js/app.js"></script>
</body>
</html>
app.js
var modalInstance = '';
var app = angular.module('TestApp', ['ui.bootstrap']);
app.controller('TestCtrl', function($scope, $http,$uibModal) {
$scope.modalOpenCtrl = function($scope, payload){
console.log('fgfdfd');
$scope.datas = payload;
console.log($scope.datas);
$scope.closeModal = function(){
console.log("this is close modal")
$scope.cancelModal();
}
}
$scope.openModal = function(task){
modalInstance = $uibModal.open({
animation: false,
templateUrl: './main_window.html',
controller: 'modalOpenCtrl',
scope: $scope,
size: 'md',
backdrop: 'static',
resolve: {
payload: function () {
return {
msg_body : 'Hello! I am payload msg',
title : 'Hello! Title',
body_title : 'UiBootstrap.net'
};
}
}
});
}
$scope.cancelModal = function(){
console.log("this is final called");
modalInstance.close();
}
});
main_window.html
<div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close" ng-click="closeModal()">
<span aria-hidden="true">×</span>
</button>
<div class="modal-title">
<h4>{{datas.title}}</h4>
</div>
</div>
<div class="modal-body log-view">
<div class="clearfix">
<h2>{{datas.body_title}}</h2>
<div>{{datas.msg_body}}</div>
</div>
</div>
<div class="modal-footer model-grey-color">
<div class="clearfix">
<div>
<button class="btn btn-success" ng-click="closeModal()">
<i class="ace-icon fa fa-ok"></i> Ok
</button>
<button class="btn btn-danger" ng-click="closeModal()">
<i class="fa fa-close"></i> Close
</button>
</div>
</div>
</div>
</div>
That's it run this code and it will be open modal on button click
Note: This is just basic setup of angularjs. We can still improve this code if you have more features to built like routing, api calls, mvc pattern
Here is medium blog which explains some basics features of angularjs.
You need to add bootstrap script to your index.html file like <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/2.5.0/ui-bootstrap-tpls.min.js"></script>

Angular not routing properly. URL is localhost:8081/#!/#pageName

I am making a simple Angular application that has an index.html which loads other HTML pages as views based on which navbar item selected; however, the routing is not working as expected. The main.html view is loaded fine, but none of the other views are loaded, and the URL is not what I expect.
The URL that shows up in the browser after an item is selected is localhost:8081/#!/#pageName. I do not know where the '!' is coming from, and there should not be a hash before the pageName. The URL that I am expecting is localhost:8081/#/pageName
app.js:
'use strict';
var app = angular.module('videoGamesApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.when('/rankedLists', {
templateUrl: 'views/rankedLists.html',
controller: 'RankedListsCtrl'
})
.when('/addGame', {
templateUrl: 'views/addGame.html',
controller: 'AddGameCtrl'
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'ContactCtrl'
})
.otherwise({
redirectTo: '/'
});
});
app.controller('MainCtrl', function($scope) {
$scope.message = 'THIS IS THE MAIN PAGE';
});
app.controller('RankedListsCtrl', function($scope) {
$scope.message = 'THIS IS THE RANKED LISTS PAGE';
});
app.controller('AddGameCtrl', function($scope) {
$scope.message = 'THIS IS THE ADD GAME PAGE';
});
app.controller('ContactCtrl', function($scope) {
$scope.message = 'THIS IS THE CONTACT PAGE';
});
index.html:
<!doctype html>
<html ng-app="videoGamesApp">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="styles/main.css">
<link rel="stylesheet" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="../bower_components/font-awesome/css/font-awesome.css">
</head>
<body ng-controller="MainCtrl">
<header>
<nav class="navbar navbar-inverse">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">GAMING </a>
</div>
<ul class="nav navbar-nav">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-trophy"></i> Ranked Lists</li>
<li><i class="fa fa-gamepad"></i> Add a Game</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
<div class="col-sm-3 col-md-3 pull-right">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search" name="sr ch-term">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
</div>
</div>
</nav>
</header>
<div id="main">
<div ng-view=""></div>
</div>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
Why are the other views not loading? Where is the exclamation point coming from in the URL? Why is there a hash before the pageName (I expect one hash, not two).
Why are the other views not loading?
The reason why your views are not loaded is because you hit the route. You use 1.6 angular and expect the behaviour from 1.5. There has been a change in location hash-prefix:
Due to aa077e8, the default hash-prefix used for $location hash-bang
URLs has changed from the empty string ('') to the bang ('!'). If your
application does not use HTML5 mode or is being run on browsers that
do not support HTML5 mode, and you have not specified your own
hash-prefix then client side URLs will now contain a ! prefix. For
example, rather than mydomain.com/#/a/b/c the URL will become
mydomain.com/#!/a/b/c.
If you actually want to have no hash-prefix, then you can restore the
previous behavior by adding a configuration block to you application:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix(''); }]); Source
What to do?
1. Set HTML5mode true
$locationProvider.html5Mode(true);
and in html set base in html header:
<base href="/">
Lastly change <a ng-href="#pagename"> to
<a ng-href="pagename">
2. Go back to old behaviour from 1.5 - set hash prefix manually
This will make your app work as you expect in your question.
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
Why is there a hash before the pageName?
The way you link is treated as a hashtag anchor tag. Which will scroll down to the current div with the given id. If you fix your problem with one of the above reasons this will be fixed aswell.

AngularJS - show and hide arrow icon with glyphicon

I have a problem with the code, all I need is to hide the "NotesText" the arrow is pointing up, and after showing the "NotesText" arrow must be pointing down. I can not find the way to make this happen, please, I need help.
Basically, I need is to change the direction of the arrow agree if I need to show or hide
This is what I have .
This is HTML:
<div id="notes-controller" class="collapse in" ng-controller="NotesController">
<fieldset>
<legend class="translatable" data-i18n="Notes">Notes</legend>
<form novalidate class="simple-form">
<div class="container col-md-12" ng-show="$ctrl.param.note.visible">
<textarea class="col-md-12" ng-readonly="$ctrl.param.note.readonly" type="text" id="Notes" ng-model="$ctrl.notes.note" ng-model-options="{ getterSetter: true }" />
</div>
</form>
</fieldset>
</div>
<span type="button" class="glyphicon glyphicon-chevron-up" data-toggle="collapse" data-target="#notes-controller"></span>
This is Controller
angular.
module('notesText').
component('notesText', {
templateUrl: '/Scripts/test/notes-text/notes-text.template.html',
bindings: {
notes: '=',
param: '='
}
}).controller('NotesController', ['$scope', function ($scope) {
$scope.master = {};
$scope.update = function (user) {
$scope.master = angular.copy(user);
};
$scope.reset = function () {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
}]);
This is how it looks:
enter image description here
A very Minimalistic Soln:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container" ng-app="">
<textarea id="myTextArea" ng-hide="isHidden">MY TEXT</textarea>
<br>
<span class="glyphicon" ng-class="isHidden ? 'glyphicon-chevron-down' : 'glyphicon-chevron-up'" ng-click="isHidden = !isHidden;">
</span>
</div>
A more verbose Soln:
Have a look at the working example below:
Simply using ng-class to attach glyphicon-chevron-up or glyphicon-chevron-down based on expression returned by a function that checks if the textarea is visible.
angular.module("myApp", [])
.controller("myCtrl", function($scope) {
$scope.isShown = function() {
return $('#myTextArea').is(':visible');
}
$scope.hideIt = function() {
$('#myTextArea').toggle();
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="myCtrl">
<textarea id="myTextArea">MY TEXT</textarea>
<br>
<span class="glyphicon"
ng-class="isShown() ? 'glyphicon-chevron-up' : 'glyphicon-chevron-down'"
ng-click="hideIt()">
</span>
</div>
Using the ng-show and ng-hide directive might be the best way to achieve this. That way you can have a scoped variable you can point to. You could also do an ng-class that if true, rotates the icon 180 degs. Either way it's up to you.
<span ng-show="$ctrl.IsToggled" type="button" class="glyphicon glyphicon-chevron-up" data-toggle="collapse" data-target="#notes-controller"></span>
<span ng-hide="$ctrl.IsToggled" type="button" class="glyphicon glyphicon-chevron-down" data-toggle="collapse" data-target="#notes-controller"></span>

Angular JS Page not loading while using session and local storage in chrome

I am new to angular js and following this tutorial http://embed.plnkr.co/dd8Nk9PDFotCQu4yrnDg/ for creating simple SPA page. In which, When I use Local and Session storage concepts in About page ,It is perfectly working in Firefox,IE except Chrome. I am not able to find the problem in Chrome. So Please need your help.
index.html
<html ng-app="scotchApp">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="./script.js" type="text/javascript"></script>
</head>
<body ng-controller="mainController">
<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">Angular Routing Example</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li><i class="fa fa-home"></i> Home</li>
<li><i class="fa fa-shield"></i> About</li>
<li><i class="fa fa-comment"></i> Contact</li>
</ul>
</div>
</nav>
</header>
<!-- MAIN CONTENT AND INJECTED VIEWS -->
<div id="main">
<div ng-view></div>
</div>
</body>
</html>
pages/about.html:
<div class="jumbotron text-center">
<h1>About Page</h1>
<p>{{ message }}</p>
<input type="button" value="Save" ng-click="Save()" />
<input type="button" value="Get" ng-click="Get()" />
</div>
pages/contact.html:
<div class="jumbotron text-center">
<h1>Contact Page</h1>
<p>{{ message }}</p>
</div>
pages/home.html:
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>
scripts.js:
var scotchApp = angular.module('scotchApp',['ngRoute','ngStorage']);
scotchApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope, $localStorage, $sessionStorage, $window) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope, $localStorage, $sessionStorage, $window) {
$scope.message = 'Look! I am an about page.';
$scope.Save = function () {
$localStorage.LocalMessage = "LocalStorage: My name is Mudassar Khan.";
$sessionStorage.SessionMessage = "SessionStorage: My name is Mudassar Khan.";
$localStorage.$save();
$sessionStorage.$save();
}
$scope.Get = function () {
$window.alert($localStorage.LocalMessage + "\n" + $sessionStorage.SessionMessage);
}
});
scotchApp.controller('contactController', function($scope, $localStorage, $sessionStorage, $window) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
Thanks In advance.
you need to serve your html via a local server .
Now Your files are being served as file:/// it should be http://
refer this stackoverflow answer

Creating a directive for bootstrap menuItems

I have built a directive for some of the boilerplate in the bootstrap navbar with ng-transclude for the navbar-collapse.I also find that there are two types of li elements for the navbar-nav items depending on whether the menu item is a dropdown or not.I find that this dropdown is however,not working.
I have built my code here in the plunker .
My JS code looks like this:
var app = angular.module('app',[]);
app.controller('main',['$scope',function($scope){
$scope.navbarOptions = {
color:'inverse',
position:'fixed-top',
collapseTarget:'navbar-ex1-collapse',
brand:'My Login',
};
$scope.menuItems=[{title:'home'},{title:'projects'},{title:'pricing'},
{
title:'Stack',
dropdown:['Java','Ruby','Javascript','Go']
}];
}]);
app.directive('bootstrapNavbar',function(){
return {
restrict:'AE',
templateUrl:'navbar.html',
scope:{
options:"="
},
transclude:true,
};
});
app.directive('bootstrapMenuitem',function(){
return {
restrict:'EA',
templateUrl:'bootstrap-menuItem.html',
scope:{
item:"#"
},
link:function(scope,element,attrs){
console.log(scope);
console.log(element);
console.log(attrs);
}
}
});
My html templates look like this:
//navbar.html
<nav class="navbar navbar-{{options.color}} navbar-{{options.position}}" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<!-- figure out a way to do toggle as an attribute directive -->
<button ng-show="options.collapseTarget" class="navbar-toggle" data-toggle="collapse" data-target=".{{options.collapseTarget}}">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">{{options.brand}}</a>
</div>
<div class="collapse navbar-collapse {{options.collapseTarget?options.collapseTarget:''}} navbar-body" ng-transclude>
</div><!-- /.navbar-collapse -->
</div>
</nav>
//bootstrap-menuItem.html
<li ng-hide="dropdown && dropdown.length">
{{item.title}}
</li>
<li ng-show="dropdown && dropdown.length" class="dropdown">
{{item.title}} <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="action in item.dropdown">{{action}}</li>
</ul>
</li>
This is my html:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Building a directive for horizontal-form using Bootstrap using Angular">
<link data-require="bootstrap#*" data-semver="3.3.1" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script data-require="jquery#*" data-semver="2.1.3" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script data-require="bootstrap#*" data-semver="3.3.1" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script data-require="angular.js#*" data-semver="1.4.0-beta.2" src="https://code.angularjs.org/1.4.0-beta.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="main">
<nav options="navbarOptions" bootstrap-navbar>
<ul class="nav navbar-nav">
<bootstrap-menuitem ng-repeat="item in menuItems" item="{{item}}"></bootstrap-menuItem>
</ul>
</nav>
</body>
</html>
The question is how do I access the item inside bootstrap-menuitem?
The template seems unable to use the item although it is in the scope?
UPDATE:
The item property accessed on the scope is a string,it needs to be an object.How can I obtain a property in the controller scope on the scope of a nested directive?
Using item:"=" instead of # causes the error http://pastebin.com/e9NDVH5b .
I assume that when using = on the bootstrap-menuitem it takes the item from ng-repeat?
However,it causes {{item.title}} to show up on the page.
In your index.html, remove double brackets in attribute item,
<bootstrap-menuitem ng-repeat="item in menuItems" item="item"></bootstrap-menuItem>
Besides, in your bootstrapMenuitem, change scope item's declaration from item: "#" to item: "=":
app.directive('bootstrapMenuitem',function(){
return {
restrict:'EA',
templateUrl:'bootstrap-menuItem.html',
scope:{
item:"="
},
link:function(scope,element,attrs){
console.log(scope);
console.log(element);
console.log(attrs);
}
}
});
This way, item can be passed to your directive's template as an object instead of plain text string.

Categories

Resources