I'm trying to write a simple angularapp to allow the teachers to edit their class information. I'm using angular-ui dialog directive to get the lightbox. On userclick I've written a function to pass the data to the modal and open the dialog. But for some reason the data is not properly binded.
This is my controller.js
'use strict';
define(['app' ], function(app) {
app.controller('TeacherClasses',
[ '$scope', '$http', '$dialog','$location', 'teacherClassService',
function($scope, $http, $dialog, $location, teacherClassService) {
$scope.newClass={};
$scope.show = {"createClassModal": false};
$http.get('/grades').success(function(data) {
$scope.grades = data;
});
$scope.newClass.grade = "Grade";
$scope.setGrade = function(grade){
$scope.newClass.grade = grade;
};
$scope.fetchStudentGroups = function(){
$http.get('/teacher/studentGroups').success(function(data) {
$scope.studentGroups = data;
});
};
$scope.fetchStudentGroups();
$scope.createClass = function(){
$http.post('/studentGroup', $scope.newClass).
success(function(data, status, headers, config) {
$scope.show.createClassModal = false;
//Clearing it out for next time
$scope.newClass = {};
$scope.fetchStudentGroups();
}).
error(function(data, status, headers, config) {
});
console.log($scope.newClass);
};
$scope.openDialog = function(studentGroup, dialog){
$scope.newClass = angular.copy(studentGroup);
$scope.opts = {
backdrop: true,
keyboard: true,
backdropClick: true,
templateUrl: '/assets/partials/teacher/manage/editClassInfo.html',
resolve: {
data: function(){
return $scope.newClass;
}
}
};
var modal = $dialog.dialog($scope.opts);
modal.open();
}
}]);
return app;
});
And this is my partial
<div class="modal-header">
Edit Class
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="control-group">
<input type="text" ng-model="newClass.name" class="span4">
</div>
<div class="control-group">
<select ui-select2 data-placeholder="Choose a grade" id="grades" class="span4">
<option></option>
<option ng-repeat="grade in grades" ng-model="grades" >{{grade}}</option>
</select>
</div>
<label>Students {{newClass.noOfStudents}}</label>
<label>{{newClass.name}}</label>
</form>
</div>
<div class="modal-footer"></div>
My module definitions are in app.js
'use strict';
define([ 'angular' ], function(angular) {
var myModule = angular.module('myApp',
[ 'ngResource', 'ui', 'infinite-scroll', 'ngDragDrop', 'blueimp.fileupload','ui.bootstrap.dialog', 'ui.bootstrap.modal',
'ui.bootstrap.dropdownToggle', 'LoadingIndicator', 'http-auth-interceptor']);
myModule.value('ui.config', {
select2 : {
allowClear : true
},
redactor: {
plugins: ['fullscreen']
}
});
return myModule;
});
But none of these values are tied back to the view. What am I doing wrong here?
Related
I want to dynamically load an angular controller upon an ajax call that renders a new view(HTML).
Here is what i have:
example of a view. HTML Snippet From AJAX
<!-- CVS Pharmacy Extracare - Add View -->
<div ng-controller="cvsViewCtrl" class="container-fluid">
<div class="col-md-8 col-md-offset-2">
<h3 id="asset-title" class=""></h3>
<br>
<p>Member ID</p>
<input class="input-s1 block-elm transition" type="text" placeholder=""/>
<br>
<input class="add-asset-btn btn btn-success block-elm transition" type="button" value="Add Asset!" ng-click="prepareCVS();"/>
</div>
</div>
the separate script that pertains to the view
App.controller('cvsViewCtrl', ['$scope', '$http', function($scope, $http){
console.log('cvs view loaded');
$scope.prepareCVS = function() {
console.log('admit one');
}
}]);
and the function that loads them
$scope.setAddAssetView = function(a) {
console.log(a);
if($scope.currentAddView == a) {
console.log('view already set');
return;
}
$scope.currentAddView = a;
$('#main-panel').html('');
$http({
method: 'POST',
url: '/action/setaddassetview',
headers: {
'Content-Type': 'application/json',
},
data: {
asset: a,
}
}).then(function(resp){
// Success Callback
// console.log(resp);
var index = resp.data.view.indexOf('<s');
var script = resp.data.view.slice(index);
var html = resp.data.view.replace(script, '');
$('#main-panel').html( html );
$('#asset-title').text(a.name);
var indexTwo = a.view.indexOf('/add');
var scriptLink = insertString(a.view, indexTwo, '/scripts').replace('.html', '.js').replace('.', '');
console.log( scriptLink );
window.asset = a;
$.getScript(scriptLink, function(data, textStatus, jqxhr){
console.log('loaded...');
})
},
function(resp){
// Error Callback
console.log(resp);
});
}
when $.getScript runs, the script gets loaded successfully but it doesn't initialize the controller. i even tried:
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = scriptLink;
s.innerHTML = null;
s.id = 'widget';
document.getElementById('switch-script').innerHTML = '';
document.getElementById('switch-script').appendChild( s );
this appends the script with the right link but still doesn't get initialized. How can i work around this?
Make this changes in your App, and be sure to load the controller file before the html with ng-controller rendered.
var App = angular.module("app", [...]);
App.config(["$controllerProvider", function($controllerProvider) {
App.register = {
controller: $controllerProvider.register,
}
}]);
App.register.controller('cvsViewCtrl', ['$scope', '$http', function($scope, $http){
console.log('cvs view loaded');
$scope.prepareCVS = function() {
console.log('admit one');
}
}]);
That would actually not be the right way to handle things.
If you use ui-router for routing, you can load the controller in the resolve function. A good service for that is ocLazyLoad.
That can be done as follows:
var app = angular.module('myApp', [
'ui.router',
'oc.lazyLoad',
]);
angular.module('myApp').config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('main', {
url: '/main',
templateUrl: 'app/views/main.view.html',
controller: 'mainCtrl',
resolve: {
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load('app/ctrls/main.ctrl.js');
}],
}
})
.state('second', {
url: '/second',
templateUrl: 'app/views/second.view.html',
controller: 'secondCtrl',
resolve: {
loadCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
return $ocLazyLoad.load('app/ctrls/controller_TWO.ctrl.js');
}],
}
})
});
When you're changing from one route to another, resolve will be triggered before the html is loaded and the controller will be registered properly.
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
};
}
I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.
Heres the html code:
<form role="form">
<div class="panel-body">
<div class="panel-body">
<img src="/assets/doge.jpg" alt="Doge">
</div>
<div class="container">
<div class="input-group">
<span class="input-group-addon" id="tec-nombre">Nombre del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.nombre" aria-describedby="tec-nombre">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-legajo">Legajo del
Tecnico:</span><input type="number" class="form-control"
data-ng-model="tecnico.legajo" aria-describedby="tec-legajo">
<div role="alert">
<span class="error"
data-ng-show="myForm.legajoTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-email">Email del
Tecnico:</span><input type="email" class="form-control"
data-ng-model="tecnico.email" aria-describedby="tec-email">
<div role="alert">
<span class="error"
data-ng-show="myForm.emailTecnico.$error.required">
Required!</span>
</div>
</div>
<div class="input-group">
<span class="input-group-addon" id="tec-interno">Interno del
Tecnico:</span><input type="text" class="form-control"
data-ng-model="tecnico.interno" aria-describedby="tec-interno">
<div role="alert">
<span class="error"
data-ng-show="myForm.nombreTecnico.$error.required">
Required!</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2"></label>
<div class="col-md-4">
Cancel
<a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary">Actualizar
{{tecnico.legajo}}</a>
<button data-ng-click="deleteCustomer(customer)"
data-ng-show="customer._id" class="btn btn-warning">Delete</button>
</div>
</div>
And heres the Angular Code:
angular.module('incidente', [ 'ngRoute' , 'ui.tree' ])
.config([ '$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl : 'partials/home.html'
}).when('/incidente/:codename', {
templateUrl : 'partials/incidente.html',
controller : 'IncidenteController'
}).when('/incidentes', {
templateUrl : 'partials/incidentes.html',
controller : 'IncidentesController'
}).when('/tecnicos', {
templateUrl : 'partials/tecnicos.html',
controller : 'TecnicosController'
}).when('/tecnico/:legajo', {
templateUrl : 'partials/tecnico.html',
controller : 'TecnicoController'
}).when('/sistema/:nombre', {
templateUrl : 'partials/sistema.html',
controller : 'SistemaController'
}).when('/sistemas', {
templateUrl : 'partials/sistemas.html',
controller : 'SistemasController'
}).when('/hardware/:codename', {
templateUrl : 'hardware.html',
controller : 'HardwareController'
}).when('/hardwares', {
templateUrl : 'partials/hardwares.html',
controller : 'HardwaresController'
}).when('/software/:codename', {
templateUrl : 'partials/software.html',
controller : 'SoftwareController'
}).when('/softwares', {
templateUrl : 'partials/softwares.html',
controller : 'SoftwaresController'
}).when('/readme', {
templateUrl : 'partials/readme.html',
controller : ''
}).when('/test', {
templateUrl : '/partials/tecnicos.html',
controller : 'TecnicosController'
}).otherwise({
redirectTo : '/'
});
} ])
.controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data;
})
})
.controller(
'navigation',
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/");
$scope.error = false;
} else {
$location.path("/login");
$scope.error = true;
}
});
};
})
.controller(
'IncidenteController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var code = $routeParams.codename;
console.log(code);
var onIncidenteComplete = function(response) {
try {
$scope.incidente = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/" + code).then(
onIncidenteComplete, onError);
$scope.saveIncidente = function(incidente) {
console.log(incidente);
return $http.post(urlbase + "set/incidente/" + incidente)
};
} ])
.controller(
'IncidentesController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onIncidenteComplete = function(response) {
try {
$scope.incidentes = angular
.fromJson(response.data);
console.log($scope.incidentes);
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/incidente/").then(
onIncidenteComplete, onError);
} ])
.controller(
'TecnicoController',
[
'$scope',
'$http',
'$routeParams',
function($scope, $http, $routeParams) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var urlbase = "http://localhost:8080/";
var legajo = $routeParams.legajo;
var onTecnicoComplete = function(response) {
try {
$scope.tecnico = response.data;
} catch (error) {
console.error(error);
}
};
$http.get(urlbase + "get/tecnico/" + legajo)
.then(onTecnicoComplete, onError);
$scope.saveTecnico = function(tecnico) {
return $http.post(urlbase + "set/tecnico/", tecnico)
};
This is the function that saves the tecnico and should show the error/success message.
} ])
.controller(
'TecnicosController',
[
'$scope',
'$http',
function($scope, $http) {
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onTecnicoComplete = function(response) {
$scope.tecnicos = response.data;
};
$http.get("http://localhost:8080/get/tecnico/")
.then(onTecnicoComplete, onError);
} ])
.controller(
'SistemasController',
[
'$scope',
'$http',
function($scope, $http) {
var urlbase = "http://localhost:8080/get/";
var onError = function(reason) {
$scope.error = "No se pudo encontrar";
};
var onSistemaComplete = function(response) {
$scope.sistemas = response.data;
};
$http.get(urlbase + "sistema/").then(
onSistemaComplete, onError);
} ]);
So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.
you could use
$scope.$on('$routeChangeStart', function(next, current) {
... you could trigger something here ...
});
and you should create a service that display something while changine route.
You have other events :
$routeChangeSuccess
$routeChangeError
$routeUpdate
HTML:
<div ng-repeat="item in productArr">
{{ item.title }}
</div>
<div category-page-navigation current-page='currentPage' category-products-count='productsCount'></div>
JS:
.controller('categoryController', ['$scope', '$location', '$http', '$q', '$window', '$stateParams', function($scope, $location, $http, $q, $window, $stateParams) {
$scope.currentPage = 1;
$scope.productsCount = 0;
var GET = {
getProductData: function() {
var defer = $q.defer();
$http.post('services/loadProduct.php', {
'id' :1,
}).then(function(response) {
defer.resolve(response);
}, function(response) {
defer.resolve([]);
});
return defer.promise;
}
};
var getData = {
getProduct: function() {
var productData = GET.getProductData();
$q.all([productData]).then(
function(response) {
$scope.productArr = response[0].data.products;
$scope.productsCount = response[0].data.products.length;
});
}
};
getData.getProduct();
}])
.directive('categoryPageNavigation', function($compile, $parse) {
return {
scope: {
currentPage: '=currentPage',
categoryProductsCount: '=categoryProductsCount'
},
link: function (scope, element, attrs) {
debugger;
// Here scope.categoryProductsCount = undefined
// ...
$scope.$watch(scope.currentPage, function(value) {
// ...
});
}
};
});
I try to form new HTML for navigation to manipulate with HTML I get from ng-repeat.
In directive I need currentPage(from start =1) and total count of items from ng-repeat(length of array) witch I get from service. How I can pass variables to directive? First I need to get variables from service(ajax request or something else) then pass variables(some ather data) to directive.
If I understood correctly what you mean. Here is a code pen example on how to shared data between you controller and your directive.
A good read to understand the code below:https://docs.angularjs.org/guide/providers
http://codepen.io/chocobowings/full/Xmzxmo/
var app = angular.module('app', []);
//-------------------------------------------------------//
app.factory('Shared', function() {
return {
sharedValue: {
value: '',
}
};
});
//-------------------------------------------------------//
app.controller('ctrl', function($scope, Shared) {
$scope.model = Shared.sharedValue;
});
//-------------------------------------------------------//
app.directive('directive', ['Shared',
function(Shared) {
return {
restrict: 'E',
link: function(scope) {
scope.model = Shared.sharedValue;
},
template: '<div><input type="text" ng-model="model.value"/></div>'
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
Ctrl:
<div ng-controller="ctrl">
<input type="text" ng-model="model.value" />
<br/>
</div>
Directive:
<directive value="model.value"></directive>
</div>
I have a framework that is supposed to be router agnostic, and while I have gotten it to work with ngRoute, I cannot for the life of me to get it to work with UI Router
The main app module Looks like this:
(function () {
"use strict";
angular.module("app", ["ptFramework", "ui.router", "ngStorage", "ui.bootstrap"]);
})();
The framework is built on three modules using custom directives the first module is the framework module
Here is the module:
(function () {
"use strict";
angular.module("ptFramework", [,"ptMenu", "ptDashboard"]);
})();
The module that I am having trouble with is the Menu module Below is the menu module:
(function () {
"use strict";
angular.module("ptMenu", ["ngAnimate"]);
})();
In index.html I have included a custom directive which looks something like this:
HTML:
<pt-menu>
<pt-menu-item label="Dasboard" icon="fa-tachometer" state="dashboard"></pt-menu-item>
<pt-menu-group label="Patients" icon="fa-users">
<pt-menu-item label="Patients" icon="fa-users" state="patient"></pt-menu-item>
<pt-menu-item label="Enter Results" icon="fa-area-chart" state="enterresults"></pt-menu-item>
<pt-menu-item label="View Results" icon="fa-area-chart" state="viewresults"></pt-menu-item>
</pt-menu-group>
<pt-menu-group label="Providers" icon="fa-user-md">
<pt-menu-item label="Providers" icon="fa-user-md" state="provider"></pt-menu-item>
<pt-menu-item label="Injury Dict." icon="fa-book" state="injurydictionary"></pt-menu-item>
<pt-menu-item label="Excercise Dict." icon="fa-book" state="excercisedictionary"></pt-menu-item>
</pt-menu-group>
<pt-menu-group label="Therapist" icon="fa-user-md">
<pt-menu-item label="Therapist" icon="fa-user-md" state="therapist"></pt-menu-item>
<pt-menu-item label="Program Entry" icon="fa-user-md" state="programentry"></pt-menu-item>
<pt-menu-item label="Results" icon="fa-area-chart" state="results"></pt-menu-item>
<pt-menu-item label="Excercises" icon="fa-bicycle" state="excercise"></pt-menu-item>
</pt-menu-group>
</pt-menu>
Here is the directive for Menu item:
(function () {
"use strict";
angular.module('ptMenu').directive('ptMenuItem', function () {
return {
require: '^ptMenu',
scope: {
label: '#',
icon: '#',
state: '#'
},
templateUrl: 'ext-modules/ptMenu/ptMenuItemTemplate.html',
link: function (scope, el, attr, ctrl) {
scope.isActive = function () {
return el === ctrl.getActiveElement();
};
scope.isVertical = function () {
return ctrl.isVertical() || el.parents('.pt-subitem-section').length > 0;
}
el.on('click', function (evt) {
evt.stopPropagation();
evt.preventDefault();
scope.$apply(function () {
ctrl.setActiveElement(el);
ctrl.setState(scope.state);
});
});
}
};
});
})();
As you can see I have state in the directive so that I can use it in my mark up. There is a el.onclick event that calls the parent controllers setState function.
That controller is here:
ptMenuController:
(function () {
"use strict";
angular.module('ptMenu').controller('ptMenuController',
['$scope', '$rootScope',
function ($scope, $rootScope) {
$scope.isVertical = true;
$scope.openMenuScope = null;
$scope.showMenu = true;
$scope.allowHorizontalToggle = true;
this.getActiveElement = function () {
return $scope.activeElement;
};
this.setActiveElement = function (el) {
$scope.activeElement = el;
};
this.isVertical = function () {
return $scope.isVertical;
}
this.setState = function (state) {
$rootScope.$broadcast('pt-menu-item-selected-event',
{ state: state });
};
This broadcasts to the next controller in the chain which is framework controller.
Framework Controller:
(function () {
"use strict";
angular.module("ptFramework").controller("ptFrameworkController",
['$scope', '$window', '$timeout', '$rootScope', '$state',
function ($scope, $window, $timeout, $rootScope, $state) {
$scope.isMenuVisible = true;
$scope.isMenuButtonVisible = true;
$scope.isMenuVertical = true;
$scope.$on('pt-menu-item-selected-event', function (evt, data) {
$scope.stateString = data.state;
$state.go(data.state);
checkWidth();
broadcastMenuState();
});
This message is getting to the front end with the correct state, but it is complaining about my controller, and when I comment out the controller I get no view
Here is the route config file
(function () {
"use strict";
angular.module('app').config([
'$stateProvider', "$urlRouterProvider", function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state("dashboard", {
url: "/dashboard",
template: "<pta-dashboard></pta-dashboard>"
})
.state("patient", {
url: "/patient",
temlateUrl: "app/patient/patientViewTemplate.html",
controller: "patientController"
})
.state("enterresults", {
url: "/enterresults",
templateUrl: "app/patient/enterResultsTemplate.html",
controller: "patientController"
})
.state("viewresults", {
url: "/viewresults",
templateUrl: "app/patient/viewResultsTemplate.html",
controller: "patientController"
})
.state("provider", {
url: "/provider",
templateUrl: "app/provider/providerVierTemplate.html",
controller: "providerController"
})
.state("injurydictionary", {
url: "/injurydictionary",
templateUrl: "app/provider/injuryDictionaryTemplate,html",
controller: "providerController"
})
.state("excercisedictionary", {
url: "/excercisedictionary",
templateUrl: "app/provider/excerciseDictionaryTemplate.html",
controller: "providerController"
})
.state("therapist", {
url: "/therapist",
templateUrl: "app/therapist/therapistViewTemplate.html",
controller: "therapistController"
})
.state("programentry", {
url: "/programentry",
templateUrl: "app/therapist/programEntryTemplate.html",
controller: "therapistController"
})
.state("results", {
url: "/results",
templateUrl: "app/results/resultsViewTemplate.html",
controller: "resultsController"
})
.state("excercise", {
url: "/excercise",
templateUrl: "app/excercise/excerciseViewTemplate.html",
controller: "excerciseController"
})
.state("programs", {
url: "/programs",
templateUrl: "app/programs/programsViewTemplate.html",
controller: "programsController"
});
$urlRouterProvider.otherwise( "/dashboard");
}
]);
})();
I am stumped on this, as is everybody I have spoken with. I have sucessfully made this work with ngRoute. I should also be getting my directive should be showing up as well. I have my ui-sref in place in the frameworkTemplate.html
<div class="pt-title-bar">
<div class="row">
<div class="pt-logo-area col-sm-6">
<img class="pt-icon" ng-src="{{ iconFile }}" />
<div class="pt-title-area">
<p class="pt-logo-title">{{ title }}</p>
<p class="pt-logo-subtitle">{{ subtitle }}</p>
</div>
<div ng-if="isMenuButtonVisible" ng-click="menuButtonClicked()"
class="pt-collapsed-menu pull-right">
<button type="button" class="btn pt-nav-button">
<i class="fa fa-bars"></i>
</button>
</div>
</div>
<div class="pt-right-side-controls col-sm-6">
<pt-user-profile-small></pt-user-profile-small>
</div>
</div>
Any thoughts or input would be appreciated, I am getting ready to abandon the broadcast all together and go to ui-srefs in the index.html. But that feels like giving up.
Thanks,
John
This is apparently a known issue with UI-Router and custom directives
https://github.com/angular-ui/ui-router/pull/858