How to get ng-model value from directive to controller in Angular? - angularjs

I created a custom directive in which I have given text box and I want to take that model value in my controller.
I tried to find it, but didn't success.
here is my directive code
app.directive("bhAddCategory", ["$rootScope", "$timeout", "CategoryFactory", "ArticleFactory", "RecentArticleFactory", "focus", function ($rootScope, $timeout, CategoryFactory, ArticleFactory, RecentArticleFactory, focus) {
return {
scope: {
display: '=bhCategoryToggle',
imageOverflow: '=bhImageOverflow',
textBoxCss: '#bhTextBoxCss',
rmText: '=bhRmText'
},
replace: true,
template: '<div>' +
'<div class="pull-left forDrop"><input type="text" focus-on="focusMe" ng-class="myColonyList" class="effect1" placeholder="Add a colony" data-ng-model="newCategoryName" data-ng-trim="true" ng-keypress="pressEnter($event)"></div>' +
'<div class="pull-right"><img src="/images/greyplus.png" ng-class="{imageoverflow: imageOverflow}" ng-show="loadplus" data-ng-click="addCategory()" alt="add category"><img src="/images/loader.gif" ng-class="{imageoverflow: imageOverflow}" alt="" ng-show="loadgif" class="colonyloder"></div >' +
'</div>',
link: function (scope, element, attrs) {
scope.loadplus = true;
scope.pressEnter = function (keyEvent) {
if (keyEvent.which === 13)
scope.addCategory();
};
scope.resetNewCategoryName = function () {
if (scope.rmText) {
scope.newCategoryName = '';
}
};
scope.addCategory = function () {
scope.display = false;
var addNewCat = scope.newCategoryName;
commonNotification($rootScope, true, false, '', '');
var categoryData = {
category_name: addNewCat,
category_type: 0
};
if (addNewCat !== undefined && addNewCat !== '') {
scope.loadgif = true;
var category_details = CategoryFactory.nameExists(addNewCat);
if (!category_details.exist) {
CategoryFactory.addAtPostion(categoryData, category_details.mid)
.then(function (category) {
scope.loadgif = false;
scope.resetNewCategoryName();
commonNotification($rootScope, false, true, true, category.success);
$timeout(function () {
$rootScope.newStatus = false;
}, 3000);
}, function (error) {
commonNotification($rootScope, false, true, true, error.message);
$timeout(function () {
$rootScope.newStatus = false;
}, 3000);
});
} else {
scope.loadgif = false;
commonNotification($rootScope, false, true, true, 'Category name already exists!');
$timeout(function () {
$rootScope.newStatus = false;
}, 2000);
}
} else {
commonNotification($rootScope, false, true, true, 'Category name is required!');
$timeout(function () {
$rootScope.newStatus = false;
}, 2000);
}
};
}
};
}]);
And here is my controller
app.controller('bookmarkCtrl', ["$scope", "$http", "$rootScope", "$timeout", "RecentArticleFactory", "CategoryFactory", "ArticleFactory", "focus", "debounce", "userFactory", function ($scope, $http, $rootScope, $timeout, RecentArticleFactory, CategoryFactory, ArticleFactory, focus, debounce, userFactory) {
}]);
Can I get any working demo, so that I can understand and implement in my code
Thanks in Advance

Use a parent scope excecution parameter on your directive.This is a scope function which is declared on your parent controller and is invoked from within your directive whenever you want to pass something to your controller.
To accomplish this we declare a scope parameter in our directive with the '&' prefix
See this example which i created for another answer
http://jsfiddle.net/jwd3gywz/26/
JS
angular.module('components', []).controller('Composer', function Composer($scope, $http) {
// adding snippet to composed text
$scope.composed_text = '';
$scope.updateCaretPosition=function(pos){
$scope.caret_position=pos;
console.log('called'+pos);
}
$scope.$watch('caret_position',function(){
console.log($scope.caret_position);
})
}).directive('caretPosition', function() {
return {
scope:{updateCaretPosition:'&'},
link: function(scope, element, attrs) {
element.bind('keyup click', function(e){
var caret_position = element[0].selectionStart;
scope.updateCaretPosition({pos:caret_position});
console.log('my current position: ' + caret_position);
});
}
}
});
angular.module('myApp', ['components'])
HTML
<!doctype html>
<html ng-app="myApp">
<body>
<div ng-controller="Composer">
<textarea class="form-control composed_text" ng-model="composed_text" update-caret-position="updateCaretPosition(pos)" caret-position="" rows="20"></textarea>
</div>
</body>
</html>

Related

Select Always Returning First Item of List (AngularJS)

No matter what I select, this function only returns the first item of the list. As requested, I have included the complete JS code. I have looked through this code four hours and everything seems right to me. This is my first contact with Angular and any help will be greatly appreciated!
Thank you!
HTML
<div class="form-horizontal input-append">
<select name="selectedSharedTenantId" data-ng-model="selectedSharedTenantId">
<option data-ng-repeat="item in getFilteredTenants()" value="{{item.id}}">{{item.displayName}}</option>
</select>
<button type="button" class="btn" ng-click="addSharedTenant();">
<i class="fas fa-plus"></i>
</button>
</div>
JS
$scope.addSharedTenant = function () {
alert($scope.selectedSharedTenantId)
}
COMPLETE JS CODE
angular.module('directives.datasetEditor', [
'services.dataset',
'ui.bootstrap'
])
.directive('datasetEditor', ['$modal', 'DatasetServices', function ($modal, DatasetServices) {
return {
restrict: 'A',
scope: {
tenantId: '=',
tenants: '=',
originalModel: '=model',
callback: '&callback'
},
link: function(scope, element, attrs) {
scope.model = scope.originalModel ? angular.copy(scope.originalModel) : {
entryType: 'Activity',
displayName: ''
};
var ModalInstanceCtrl = ['$scope', '$modalInstance',
function($scope, $modalInstance) {
var setSelectedSharedTenantId = function () {
var selectedTenant = $scope.getFilteredTenants()[0];
$scope.selectedSharedTenantId = selectedTenant ? selectedTenant.id : null;
};
$scope.getFilteredTenants = function () {
return _.filter($scope.tenants, function (o) {
alert(o.id)
return _.indexOf($scope.model.sharedTenantIds, o.id) == -1 && o.id != $scope.tenantId;
});
};
$scope.getTenantById = function (id) {
return _.findWhere($scope.tenants, {
id: id
});
};
$scope.removedSharedTenant = function (id) {
$scope.model.sharedTenantIds = _.without($scope.model.sharedTenantIds, id);
var selectedTenant = $scope.getFilteredTenants()[0];
setSelectedSharedTenantId();
};
$scope.addSharedTenant = function () {
//alert($scope.selectedSharedTenantId)
//alert($scope.model.sharedTenantIds)
if ($scope.selectedSharedTenantId) {
if ($scope.model.sharedTenantIds == null) {
$scope.model.sharedTenantIds = [];
}
$scope.model.sharedTenantIds.push($scope.selectedSharedTenantId);
setSelectedSharedTenantId();
}
};
$scope.submit = function(isValid) {
if (isValid) {
DatasetServices.save($scope.model).success(function(data, status, headers, config) {
$modalInstance.close(data);
});
} else {
$scope.submitted = true;
}
};
$scope.cancel = function() {
$modalInstance.dismiss();
};
$scope.submitted = false;
setSelectedSharedTenantId();
}];
function open() {
var modalInstance = $modal.open({
templateUrl: '../pkg/wisdom/common/angular/directives/dataset-editor/index.html',
controller: ModalInstanceCtrl,
scope: scope
});
modalInstance.result.then(
function(model) {
scope.callback({
model: model
});
},
function() {
}
);
};
element.on('click', open);
}
};
}]);

Angular JS watch factory variable

I have a factory variable which is shared by two directives. One directives changes it and I need it to update the value in other directive as well.
This is my factory code
commonApp.factory('setSmsMessage', [function () {
var factoryObj = {
data: {
isSms: false
},
setSms: function () {
factoryObj.data.isSms = true;
},
reset: function () {
factoryObj.data.isSms = false;
}
};
return factoryObj;
}]);
This is my one directive
commonApp.directive('osSendMessage', ['setSmsMessage',
function (setSmsMessage) {
return {
restrict: 'A',
scope: {
sent: '='
},
link: function (scope, element, attrs) {
},
controller: function ($scope) {
$scope.setSmsMessage = setSmsMessage.data;
$scope.$watch('setSmsMessage.isSms', function (newValue, oldValue, scope) {
console.log(setSmsMessage.data.isSms);
}, true);
},
templateUrl: "/Static/js/AngularApps/MessageCenter/sendmessage/Templates/sendmessages.html"
};
}]);
This is my other directive which sets the variable
commonApp.directive('osMessageCenterMenu', ['setSmsMessage', function (setSmsMessage) {
return {
restrict: 'A',
scope: {
messages: "="
},
controller: function ($scope) {
},
link: function (scope) {
// opening sms
$("#toggleSendSmsMessage").click(function () {
scope.openSendSms();
});
scope.openSendSms = function () {
console.log("from menu: " + setSmsMessage.data.isSms);
setSmsMessage.setSms();
console.log("from menu: " + setSmsMessage.data.isSms);
$("#SendMessageForm").toggle();
}
// end here
,
templateUrl: "/Static/js/AngularApps/MessageCenter/Templates/messageCenterMenu.html"
};
}]);
But the value is not updated in the other controller which is listening to it
A better way would be to store the isSms property in a global object like so:
commonApp.factory('setSmsMessage', [function ()
{
var factoryObj = {
data: {
isSms: false
},
setSms: function ()
{
factoryObj.data.isSms = true;
},
reset: function ()
{
factoryObj.data.isSms = false;
}
};
return factoryObj;
}]);
Now in your controller link the $scope to the factories global object which holds the isSms property.
// Link setSmsMessage to the factories data object
$scope.setSmsMessage = setSmsMessage.data;
// Now call the setSms() function. The $scope.setSmsMessage will be updated after the call.
setSmsMessage.setSms();
// You can now watch for changes in the $scope like so
$scope.$watch('setSmsMessage.isSms', function (newValue, oldValue, scope) {
console.log(setSmsMessage.data.isSms);
}, true);
Working demo
(function() {
var commonApp = angular.module("app", []);
commonApp.factory('setSmsMessage', [function ()
{
var factoryObj = {
data: {
isSms: false
},
setSms: function ()
{
factoryObj.data.isSms = true;
},
reset: function ()
{
factoryObj.data.isSms = false;
}
};
return factoryObj;
}]);
commonApp.controller("smsController", function($scope, setSmsMessage) {
// Link setSmsMessage to the factories data object
$scope.setSmsMessage = setSmsMessage.data;
// Now call the setSms() function. The $scope.setSmsMessage will be updated after the call.
setSmsMessage.setSms();
$scope.reset = function()
{
setSmsMessage.reset();
}
$scope.$watch('setSmsMessage.isSms', function (newValue, oldValue, scope) {
console.log(setSmsMessage.data.isSms);
}, true);
});
commonApp.directive('osMessageCenterMenu', ['setSmsMessage', function (setSmsMessage)
{
return {
restrict: 'A',
scope: {
messages: "="
},
controller: function ($scope)
{
},
link: function (scope)
{
console.log(scope);
// opening sms
$("#toggleSendSmsMessage").click(function ()
{
scope.openSendSms();
});
scope.openSendSms = function ()
{
console.log("from menu: " + setSmsMessage.data.isSms);
setSmsMessage.setSms();
console.log("from menu: " + setSmsMessage.data.isSms);
$("#SendMessageForm").toggle();
}
}
}
}]);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="smsController">
<div os-message-center-menu>
<button id="toggleSendSmsMessage">reset message</button>
</div>
</div>
</div>
you can also work with $rootScope in your factory and emit an event with custom data and then subscribe to the event in all your controllers
Also, try naming your factory based on functionality, for obvious
reasons.
Following is what am trying to say :-
(function() {
angular
.module("myApp", [])
.factory('smsMessage', ['$rootScope', function($rootScope) {
var factoryObj = {
data: {
isSms: false
},
setSms: function() {
factoryObj.data.isSms = true;
$rootScope.$emit('SET', {isSms : true});
},
reSet: function() {
factoryObj.data.isSms = false;
$rootScope.$emit('RE-SET', {isSms : false});
}
};
return factoryObj;
}])
.controller("controllerOne", function($scope, $rootScope, smsMessage) {
$scope.setSmsMessage = smsMessage.data;
$scope.set = function(){
smsMessage.setSms();
}
$scope.reset = function(){
smsMessage.reSet();
}
$rootScope.$on('SET', function(event, data) {
alert('SET in controllerOne');
$scope.setSmsMessage = data.isSms;
});
$rootScope.$on('RE-SET', function(event, data) {
alert('RE-SET in controllerOne');
$scope.setSmsMessage = data.isSms;
});
})
.controller("controllerTwo", function($scope, $rootScope, smsMessage) {
$scope.setSmsMessage = smsMessage.data;
$scope.set = function(){
smsMessage.setSms();
}
$scope.reset = function(){
smsMessage.reSet();
}
$rootScope.$on('SET', function(event, data) {
alert('SET in controllerTwo');
$scope.setSmsMessage = data.isSms;
});
$rootScope.$on('RE-SET', function(event, data) {
alert('RE-SET in controllerTwo');
$scope.setSmsMessage = data.isSms;
});
});
})()
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="controllerOne">
<label>Controller One</label>
<button ng-click="set()">SET</button>
<button ng-click="reset()">RE-SET</button>
</div>
<div ng-controller="controllerTwo">
<label>Controller Two</label>
<button ng-click="set()">SET</button>
<button ng-click="reset()">RE-SET</button>
</div>
</div>

isolate scope communication from directive to directive?

I am new to AngularJS and got confused with directive concept.
I am updating scope.markers in my second directive via $scope.delete function but changes are not reflecting on first directives,as I am using two way data binding isolate scope, so it should reflect. any solution will be a great help.
I have my first directive as:
app.directive('damageDiagram', function () {
return {
retrict: 'AE',
scope: {
imgsrc: '=', markers: '=', pointsrc: '=', dtype:'='
},
templateUrl: 'app/components/inspections/damage-diagram.html',
link: function (scope, element, attrs) {
}
}
});
and second directive as:
app.directive('damageMarker', function ($mdDialog,inspectionService,$timeout) {
return {
restrict: 'AE',
require: '?^damageDiagram',
scope: {
marker: '=',
pointsrc: '=',
dtype:'=',
markers: '='
},
template: '<img ng-src="{{pointsrc}}" />',
link: function (scope, elem, attr) {
elem.on("click",function(e){
showDialog();
function showDialog($event) {
var parentEl = angular.element(document.body);
$mdDialog.show ({
parent: parentEl,
targetEvent: $event,
template:
'<form name="clientForm" novalidate >'+
'<md-dialog aria-label="List dialog">' +
' <md-dialog-content>'+
'<md-input-container>'+
'<md-select ng-model="dtypeValue" class="dialog-close" placeholder="Select dtype">'+
'<md-option ng-repeat="opt in dtype">{{opt}}</md-option>'+
'</md-select>'+
'</md-input-container>'+
'<md-input-container class="md-block">'+
'<label>Comment</label>'+
'<input required name="name" ng-model="comment" class="dialog-close">'+
'<div ng-messages="clientForm.name.$error">'+
'<div ng-message="required">This is required.</div>'+
'</div>'+
'</md-input-container>'+
' </md-dialog-content>' +
' <div class="md-actions" layout="row" layout-align="end center">' +
' <md-button ng-click="closeDialog()" class="md-primary">' +
' Close' +
' </md-button>' +
'<md-button ng-disabled="clientForm.$invalid" ng-click = "save()" class="md-primary">'+
'Save'+
'</md-button>'+
'<md-button ng-disabled="clientForm.$invalid" ng-click = "delete()" class="md-primary">'+
'Delete'+
'</md-button>'+
' </div>' +
'</md-dialog>'+
'</form>',
controller: DialogController
});
function DialogController($scope, $mdDialog) {
$scope.dtypeValue = scope.dtype[scope.marker.dtype.toUpperCase()];
$scope.dtype = scope.dtype;
$scope.comment = scope.marker.comment;
$scope.marker = scope.marker;
$scope.closeDialog = function() {
$mdDialog.hide();
}
$scope.save = function(){
console.log($scope.marker.id);
console.log($scope.dtypeValue);
console.log($scope.comment);
var dataSend = {};
dataSend.id = $scope.marker.id;
dataSend.comment = $scope.comment;
for(var key in $scope.dtype) {
if($scope.dtype[key] == $scope.dtypeValue) {
dataSend.dtype = key;
}
}
inspectionService.updateDiagram(dataSend).then(function(response){
console.debug("response ; "+response);
$mdDialog.hide();
scope.marker.id = response.id;
scope.marker.comment = response.comment;
scope.marker.dtype = response.dtype;
});
}
$scope.delete = function(){
var dataSend = {};
dataSend.id = $scope.marker.id;
var param = {};
param.inspection=$scope.marker.inspection;
inspectionService.deleteDiagramMarker(dataSend).then(function(response){
inspectionService.getDiagram(param).then(function(response){
$timeout(function() {
scope.$apply(function(){
scope.markers = response.results;
})
},2000);
console.debug("response ; "+response);
$mdDialog.hide();
});
});
}
}
}
});
console.log(scope.marker.top, scope.marker.left, elem);
}
}
});
My html code for damage-diagram directive is as follows:
<damage-diagram imgsrc="imgsrc" pointsrc="pointsrc" dtype="dtype"
markers="inspection.damage_diagram">
</damage-diagram>
and my html code for damage-directive is as follow:
<div style="position:relative">
<img id="23467129" ng-src="{{imgsrc}}" style="position:relative" width="100%" />
<div ng-repeat="marker in markers"
marker="marker"
markers="markers"
dtype="dtype"
pointsrc="pointsrc"
damage-marker>
</div>
</div>
controller is as follows:
app.controller('InspectionDetailCtrl', ['$scope', 'inspectionService', '$stateParams', 'Restangular','$rootScope',
function ($scope, inspectionService, $stateParams, Restangular, $rootScope) {
$scope.updateDamageImage = {};
$scope.insp_id = $stateParams.inspId;
$scope.damageImagesShow = false;
$scope.comments = [];
$scope.types = [];
$scope.selectTypeDelete = false;
$scope.commentDelete = false;
$scope.selectTypeDeleteBefore = true;
$scope.commentDeleteBefore = true;
init($scope.insp_id);
console.log("Fetching details for scope", $scope.insp_id);
function init(insp_id)
{
inspectionService.inspections.customGET(insp_id, {type: 'full'})
.then(function (data) {
$scope.inspection = data;
}, function (err) {
$scope.inspection = null;
});
}
$scope.pointsrc="app/components/inspections/pointer.png";
$scope.dtype = {
'S': 'Scratch (minor)',
'DS': 'Deep Scratch',
'D': 'Dents',
'WD': 'Wheel Damage',
'CW': 'Cracked Window',
'FT': 'Flat Tire',
'BL': 'Broken (lights)'
};
}]);
First of all two way binding in directive doesn't works like that any change reflected in main controller can be seen in directive but not other way any change in directive won't be reflected in main controller.
But there is a solution you can create an object in main controller
var x={};
x.value='to be passed in directive'
then you use same variable in directive since only once instance of object is created so any change in any directive will be reflected everywhere.

How to call function in directive from button click

How do I call a function in a directive from a button click? I have been trying and have come up with this (but it is not working):
HTML
<div ng-controller="myMapCTRL as myMapctrl">
<div id="panel">
<input ng-click="updateMap()" type=button value="Remove Path">
</div>
<my-map-with-path id="map-canvas" class="map-canvas" ng-if="dataHasLoaded" ></my-map-with-path>
</div>
Controller
app.controller('myMapCTRL', ['$scope', 'PathService', function($scope, PathService){
//console.log('in controller');
$scope.removed = false;
if(typeof $scope.paths ==='undefined') {
$scope.dataHasLoaded = false;
$scope.center = new google.maps.LatLng(51.5130300, -0.3202410);
PathService.getPaths().then(function(data){
$scope.paths = data;
$scope.dataHasLoaded = true;
//console.log('paths loaded');
});
};
}]);
Directive
app.directive('myMapWithPath', [function() {
return{
restrict: 'AE',
template: '<div></div>',
replace: true,
controller: 'myMapCTRL',
link: function(scope, element, attrs){
//console.log('in link');
scope.updateMap = function() {
console.log('inside updateMap()');
}
var map, path = new google.maps.MVCArray(),
service = new google.maps.DirectionsService(), poly;
//var center = new google.maps.LatLng(51.5130300, -0.3202410);
var myOptions = {
zoom: 15,
center: scope.center,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.HYBRID,
google.maps.MapTypeId.SATELLITE]
},
disableDoubleClickZoom: true,
scrollwheel: false,
draggableCursor: "crosshair"
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
poly = new google.maps.Polyline({ map: map });
for(var i = 0; i < scope.paths['j'].length; i++) {
var lat = scope.paths['j'][i]['k']
var lng = scope.paths['j'][i]['D']
var lat_lng = new google.maps.LatLng(lat, lng);
path.push(lat_lng);
}
poly.setPath(path);
google.maps.event.addListener(map, "click", function(evt) {
if (path.getLength() === 0) {
path.push(evt.latLng);
poly.setPath(path);
} else {
service.route({
origin: path.getAt(path.getLength() - 1),
destination: evt.latLng,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length;
i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
//console.log(path);
});
}
}
}]);
I want to call scope.updateMap from the button click but it is not firing in the console.
This won't work because the ng-click is outside the directive.
You should move the function updateMap to the $scope of myMapCTRL
Having dug around a little more, it seems quite normal to use a shared service to communicate between a controller and a directive.
The general idea is this:
HTML
<div ng-controller="myMapCTRL as myMapctrl">
<div id="panel">
<input ng-click="updateMap()" type=button value="Remove Path">
</div>
<my-map-with-path id="map-canvas" class="map-canvas" ng-if="dataHasLoaded" ></my-map-with-path>
</div>
SharedService
app.factory('mySharedService', function($rootScope) {
var sharedService = {};
sharedService.doSomething = function() {
$rootScope.$broadcast('messageBroadcast');
};
return sharedService;
});
Controller
app.controller('myMapCTRL', ['$scope', 'mySharedService',
function($scope, sharedService){
$scope.updateMap = function() {
sharedService.doSomething();
}
}]);
Directive
app.directive('myMapWithPath', [function() {
return{
restrict: 'AE',
template: '<div></div>',
replace: true,
controller: 'myMapCTRL',
link: function(scope, element, attrs){
scope.$on('messageBroadcast', function() {
console.log('in directive broadcast message');
});
...
}
}
}]);
The idea seems to be that the controller calls a function in the shared service which "broadcasts" a message out. The directive waits for that message and when it is received, it does something amazing.
I am not sure if I need to inject the shared service into the directive or link function but it seems to work without it.

Directive inside $modal window throws "undefined is not a function"

Using ui-bootstrap I have a really simple custom directive that lists alerts at the top of the page. On normal pages it works like a champ. When I use my directive inside a $modal popup I get "undefined is not a function" at ngRepeatAction.
The directive I have behind the modal on the main page still works. I can see it behind the modal. It's just the one in the modal popup that breaks. What am I doing wrong?
Modal open code:
$modal.open({
templateUrl: 'partials/main/servers/serverAuths/edit.html',
controller: function($scope, $modalInstance) {
$scope.auth = angular.copy(auth);
$scope.auth.password = null;
$scope.saveAuth = function() {
Auths.editAuth($scope.auth).then(
function(resp) {
if (resp.rc===0) {
Alerts.addAlert('success', 'Auth `'+$scope.auth.name+'` saved.');
_.extend(auth, $scope.auth);
$modalInstance.close();
} else {
Alerts.addAlert('danger', 'Auth `'+$scope.auth.name+'` could not be saved. ' + resp.message, 'serverAuths');
}
}
);
};
$scope.resetAuth = function() {
$modalInstance.close();
};
}
}).result.then(
function() {
Auths.getAuthList().then(
function(resp) {
$scope.auths = resp;
}
);
}
);
Directive template:
<div class="alert-wrapper alert-{{ alert.type }}"
ng-repeat="alert in alerts"
ng-class="{ 'relative':relative }">
<div class="container">
<div alert type="alert.type" close="closeAlert($index)">{{alert.msg}}</div>
</div>
</div>
Directive code:
angular.module('app')
.directive('appAlerts', function() {
return {
restrict: 'A',
replace: true,
scope: {
watchForm: '=',
relative: '#'
},
templateUrl: 'partials/directives/appAlerts.html',
controller: function($scope, Alerts) {
$scope.closeAlert = function(idx) { Alerts.closeAlert(idx); };
$scope.alerts = Alerts.getAlerts();
}
};
});
Alerts Factory:
angular.module('app').factory('Alerts', function($timeout) {
var alerts = [];
function timeoutAlert(a) {
$timeout(function() {
a.splice(0, 1);
}, 2500);
}
var addAlert = function(type, msg) {
alerts.push({type:type, msg:msg});
timeoutAlert(alerts);
};
var closeAlert = function(index) {
alerts.splice(index, 1);
};
var getAlerts = function() {
return alerts;
};
var killAlert = function(msg) {
var alert = _.where(alerts, {msg:msg});
var idx = _.indexOf(alerts, alert[0]);
if (idx > -1) {
closeAlert(idx);
}
};
return {
addAlert:addAlert,
closeAlert:closeAlert,
getAlerts:getAlerts,
killAlert:killAlert
};
});

Resources