I have these 2 services:
.factory('HttpHandler', function() {
return {
loadData: function (promise) {
var self = {
data: [],
loading: true,
promise: promise
};
promise.then(function (data) {
self.data = data;
self.loading = false;
});
promise.finally(function () {
self.loading = false;
});
return self;
}
};
})
.factory('Order', ['$resource', '$filter', 'apiUrl', function ($resource, $filter, api) {
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
}
}, {
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
}
}, {
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
angular.extend(Order.prototype, {
getDescription: function () {
var rolls = 0,
cuts = 0,
skus = [],
lines = $filter('orderBy')(this.lines, 'sku');
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
switch (line.type) {
case 0: // cut
cuts++;
break;
case 1: // roll
rolls++
break;
}
if (skus.indexOf(line.sku) == -1) {
skus.push(line.sku);
}
}
var description = '';
description += cuts > 0 ? cuts > 1 ? cuts + ' x cuts' : cuts + ' x cut' : '';
description += rolls > 0 && description.length > 0 ? ', ' : '';
description += rolls > 0 ? rolls > 1 ? rolls + ' x rolls' : rolls + ' x roll' : '';
description += skus.length == 1 ? ' of ' + skus[0] : '';
return description;
}
});
return Order;
}]);
As you can see, I have defined 3 different paths to use:
orders/recent
orders/failures
orders/exceptions
I have this controller:
.controller('CustomerServicesController', ['HttpHandler', 'Order', function (handler, Order) {
var self = this;
self.recent = handler.loadData(Order.recent({ limit: 30 }).$promise);
self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);
self.exceptions = handler.loadData(Order.exceptions({ limit: 30 }).$promise);
}])
When I run my application, I get an error stating:
undefined is not a function
on the line that states self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);.
If I comment out the 2 lines so the controller becomes:
.controller('CustomerServicesController', ['HttpHandler', 'Order', function (handler, Order) {
var self = this;
self.recent = handler.loadData(Order.recent({ limit: 30 }).$promise);
//self.failures = handler.loadData(Order.failures({ limit: 30 }).$promise);
//self.exceptions = handler.loadData(Order.exceptions({ limit: 30 }).$promise);
}])
Everything works fine....
I think it has something to do with the $resource but I can't figure it out.
Just for completeness sake, here is the template file:
<div class="row">
<a class="back" href="/"><i class="fa fa-arrow-circle-left"></i></a>
<section class="large-4 columns">
<h1 class="column-title">Orders <small>quick search</small></h1>
<form name="orderFrom" role="form" ng-submit="customerServices.orderSearch()">
<div class="row collapse">
<div class="small-10 columns typeahead-icon">
<input type="text" ng-model="customerServices.searchTerm" placeholder="Search" typeahead="item for items in customerServices.autoComplete() | filter:$viewValue" typeahead-loading="customerServices.loading" typeahead-min-length="2">
<i ng-show="customerServices.loading" class="fa fa-spinner fa-spin"></i>
</div>
<div class="small-2 columns">
<button type="submit" class="button postfix">Go</button>
</div>
</div>
</form>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Recent orders</h1>
<div class="loading" ajax-loader ng-show="customerServices.recent.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.recent.loading && customerServices.recent.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.recent.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Sync failures</h1>
<div class="loading" ajax-loader ng-show="customerServices.failures.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.failures.loading && customerServices.failures.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.failures.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
<section class="tile-column large-8 columns" tile-column>
<h1 class="column-title">Exceptions</h1>
<div class="loading" ajax-loader ng-show="customerServices.exceptions.loading"></div>
<div class="alert alert-box" ng-show="!customerServices.exceptions.loading && customerServices.exceptions.data.length === 0">
No records have been found that match your search.
×
</div>
<a class="tile large" ng-href="/customer-services/view-order/{{order.orderNumber}}" tile ng-repeat="order in customerServices.exceptions.data" id="{{order.orderNumber}}">
<div class="text">
<strong ng-bind="order.account.accountNumber"></strong> <span ng-bind="order.account.name"></span><br />
<span ng-bind="order.raisedBy"></span><br />
<span ng-bind="order.orderNumber"></span><br />
<span ng-bind="order.getDescription()"></span><br />
</div>
</a>
</section>
</div>
Can anyone tell me why this isn't working?
Figured it out, it was a syntax error on my part in the Order service. It should be:
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
},
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
},
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
and NOT
var Order = $resource(api + 'orders/:path', {
path: '#path'
}, {
recent: {
method: 'GET',
params: {
path: 'recent'
},
isArray: true
}
}, {
failures: {
method: 'GET',
params: {
path: 'failures'
},
isArray: true
}
}, {
exceptions: {
method: 'GET',
params: {
path: 'exceptions'
},
isArray: true
}
});
subtle difference :)
Related
I have angular list and want to get selected value of it but its only working on click event
<div ng-hide="hideCustomerDropdown" id="customer-dropdown" class="slidedown-menu">
<div class="slidedown-header">
</div>
<div class="slidedown-body">
<ul class="customer-list list-unstyled">
<li ng-repeat="customers in customerArray" >
<span class="fa fa-fw fa-user"></span>{{ customers.customer_name }} ({{ customers.customer_mobile || customers.customer_email }})
</li>
</ul>
</div>
</div>
controller:
$("#customer-name").on("click", function() {
$scope.showCustomerList(true);
});
$scope.showCustomerList = function (isClick) {
$http({
url: API_URL ,
method: "GET",
cache: false,
processData: false,
contentType: false,
dataType: "json"
}).
then(function(response) {
$scope.hideCustomerDropdown = false;
$scope.customerArray = [];
window.angular.forEach(response.data, function(customerItem, key) {
if (customerItem) {
$scope.customerArray.push(customerItem);
}
});
}, function(response) {
window.toastr.error(response.data.errorMsg, "Warning!");
});
};
Not sure to understand your question but try to re-render your template by adding
$scope.$apply();
at the end of your then function.
I have a modal view(.jsp) that has integrated directive (named as 'querybuilder', Yellow part in the picture - a js file). Controller(named as 'addEditRuleSetCtrl') and directive is included from upper level and inclusion seems fine. We have initiated the directive from the view as :
<div ng-init="addEditRuleSetCtrl.initSelectors()">
<query-builder group="addEditRuleSetCtrl.filter.group"
rule-condition-operators="addEditRuleSetCtrl.ruleConditionOperators"
rule-condition-set-operators="addEditRuleSetCtrl.ruleConditionSetOperators"
fields="addEditRuleSetCtrl.fieldCodes"
></query-builder>
</div>
Where "addEditRuleSetCtrl.initSelectors()" initiates all the params passed to the directive as :
self.initSelectors = function()
{
self.getRuleConditionOperators();
self.getRuleConditionSetOperators();
self.fieldCodes = self.getCorrespondingFields();
console.log("initSelectors : fieldCodes: " + JSON.stringify(self.fieldCodes ));
}
self.getCorrespondingFields = function()
{
return self.origin == 'DDE' ? self.fieldsDDE : self.fieldsATT;
};
And the params were declared in the controller in this way:
self.fieldsDDE = [
{ name: 'FirstnameDDE' },
{ name: 'LastnameDDE' },
{ name: 'BirthdateDDE' },
{ name: 'CityDDE' },
{ name: 'CountryDDE' }
];
self.fieldsATT = [
{ name: 'FirstnameATT' },
{ name: 'LastnameATT' },
{ name: 'BirthdateATT' },
{ name: 'CityATT' },
{ name: 'CountryATT' }
];
self.fieldCodes = [];
self.ruleConditionSetOperators = [];
self.ruleConditionOperators = [];
The problem is: one ( the param 'fieldCodes')of the four params that passed to the directive is "undefined" Although they were defined ,passed in similar way. I have cleaned the cache and tested all possible ways but nothing made any difference.As a result the associated dropdown is empty (in the red-arrowed dropdown in the screenshot).Any clue?
The full view :
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<link
href="<c:url value='aviato/ruleEngine/addEditRuleSet/css/addeditruleset.css' />"
rel="stylesheet">
</link>
<%--<script src="aviato/ruleEngine/addEditRuleSet/directive/addEditRuleSet_directive.js"></script>--%>
<form name="addEditRuleSetModalForm" novalidate class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
{{addEditRuleSetCtrl.windowHeader}}
<button type="button" class="btn btn-danger btn-sm pull-right"
ng-click="addEditRuleSetCtrl.close()" data-toggle="uibtooltip" title="Cancel" >
<span class="glyphicon glyphicon-remove-sign"></span>
</button>
</h4>
</div>
<div class="modal-body">
Hello world [origin] : {{ addEditRuleSetCtrl.origin }}
<br />
Hello world [iceField] : {{ addEditRuleSetCtrl.iceField }}
Output: {{ addEditRuleSetCtrl.output }}
<div class="alert alert-info">
<strong>Example Output</strong><br>
Output: {{ addEditRuleSetCtrl.output }}
</div>
<div ng-init="addEditRuleSetCtrl.initSelectors()">
<query-builder group="addEditRuleSetCtrl.filter.group"
rule-condition-operators="addEditRuleSetCtrl.ruleConditionOperators"
rule-condition-set-operators="addEditRuleSetCtrl.ruleConditionSetOperators"
fields="addEditRuleSetCtrl.fieldCodes"
></query-builder>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-sm" ng-click="addEditRuleSetCtrl.test()" data-toggle="tooltip" ><span class="glyphicon glyphicon-ok-sign" ></span></button><span></span>
</div>
</div>
</form>
<script type="text/ng-template" id="/queryBuilderDirective.html">
<div class="alert alert-warning alert-group">
<div class="form-inline">
<select ng-options="o as o.operator for o in ruleConditionSetOperators" ng-model="group.operator" class="form-control input-sm"></select>
<button style="margin-left: 5px" ng-click="addCondition()" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-plus-sign"></span> Add Condition</button>
<button style="margin-left: 5px" ng-click="addGroup()" class="btn btn-sm btn-success"><span class="glyphicon glyphicon-plus-sign"></span> Add Group</button>
<button style="margin-left: 5px" ng-click="removeGroup()" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span> Remove Group</button>
</div>
<div class="group-conditions">
<div ng-repeat="rule in group.rules | orderBy:'index'" class="condition">
<div ng-switch="rule.hasOwnProperty('group')">
<div ng-switch-when="true">
<query-builder group="rule.group"
rule-condition-operators="addEditRuleSetCtrl.ruleConditionOperators"
rule-condition-set-operators="addEditRuleSetCtrl.ruleConditionSetOperators"
fields="addEditRuleSetCtrl.fieldCodes"
></query-builder>
</div>
<div ng-switch-default="ng-switch-default">
<div class="form-inline">
<select ng-options="t.name as t.name for t in fields" ng-model="rule.field" class="form-control input-sm"></select>
<select style="margin-left: 5px" ng-options="c as c.operator for c in ruleConditionOperators" ng-model="rule.condition" class="form-control input-sm"></select>
<input style="margin-left: 5px" type="text" ng-model="rule.data" class="form-control input-sm"/>
<button style="margin-left: 5px" ng-click="removeCondition($index)" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span></button>
</div>
</div>
</div>
</div>
</div>
</div>
</script>
The Directive:
AddEditRuleSetApp.directive('queryBuilder', ['$compile', function ($compile) {
return {
restrict: 'E',
scope: {
group: '=',
ruleConditionOperators: '=',
ruleConditionSetOperators: '=',
fields: '='
},
templateUrl: '/queryBuilderDirective.html',
compile: function (element, attrs) {
var content, directive;
content = element.contents().remove();
return function (scope, element, attrs) {
scope.fields = scope.$parent.fieldCodes;
scope.ruleConditionOperators = scope.$parent.ruleConditionOperators;
scope.ruleConditionSetOperators = scope.$parent.ruleConditionSetOperators;
window.alert("HEYYYYYY I'M CHANGING!!!!!! "
+ JSON.stringify(scope.group)
+ " ; "+ JSON.stringify(scope.ruleConditionOperators)
+ " ; "+ JSON.stringify(scope.ruleConditionSetOperators)
+ " ; "+ JSON.stringify(scope.fields));
scope.addCondition = function () {
scope.group.rules.push({
condition: '=',
field: 'Firstname',
data: ''
});
};
scope.removeCondition = function (index) {
scope.group.rules.splice(index, 1);
};
scope.addGroup = function () {
scope.group.rules.push({
group: {
operator: 'AND',
rules: []
}
});
};
scope.removeGroup = function () {
"group" in scope.$parent && scope.$parent.group.rules.splice(scope.$parent.$index, 1);
};
directive || (directive = $compile(content));
element.append(directive(scope, function ($compile) {
return $compile;
}));
}
}
}
}]);
The controller:
AddEditRuleSetApp.controller( 'AddEditRuleSetModalController', [ '$scope', '$rootScope', '$uibModalInstance','RuleEngineService', 'origin', 'iceField','FileService',
function( $scope, $rootScope , $uibModalInstance, RuleEngineService, origin, iceField, FileService )
{
var self = this;
self.origin = origin;
self.iceField = iceField;
self.data = '{"group": {"operator": "AND","rules": []}}';
self.output = 'bologna';
self.filter = JSON.parse(self.data);
self.fieldsDDE = [
{ name: 'FirstnameDDE' },
{ name: 'LastnameDDE' },
{ name: 'BirthdateDDE' },
{ name: 'CityDDE' },
{ name: 'CountryDDE' }
];
self.fieldsATT = [
{ name: 'FirstnameATT' },
{ name: 'LastnameATT' },
{ name: 'BirthdateATT' },
{ name: 'CityATT' },
{ name: 'CountryATT' }
];
self.fieldCodes = [];
self.ruleConditionSetOperators = [];
self.ruleConditionOperators = [];
self.initSelectors = function()
{
self.getRuleConditionOperators();
self.getRuleConditionSetOperators();
self.fieldCodes = self.getCorrespondingFields();
console.log("initSelectors : fieldCodes: " + JSON.stringify(self.fieldCodes ));
}
self.getRuleConditionOperators = function()
{
if ( self.ruleConditionOperators.length == 0 )
{
RuleEngineService.getAllRuleConditionOperators()
.then(
function( d )
{
self.ruleConditionOperators = d;
},
function( errResponse )
{
console.error( 'Error while fetching rule-condition-operators' );
}
);
}
return self.ruleConditionOperators;
};
self.getRuleConditionSetOperators = function()
{
if ( self.ruleConditionSetOperators.length == 0 )
{
RuleEngineService.getAllRuleConditionSetOperators()
.then(
function( d )
{
self.ruleConditionSetOperators = d;
},
function( errResponse )
{
console.error( 'Error while fetching rule-condition-operators' );
}
);
}
return self.ruleConditionSetOperators;
};
self.htmlEntities = function(str)
{
return String(str).replace(/</g, '<').replace(/>/g, '>');
};
self.displayErrorMessages = false;
self.createSuccess = '';
self.createHeader = '';
self.backendErr = "";
self.windowHeader = "Create/Edit Rule Group";
self.close = function()
{
$uibModalInstance.close();
};
self.getCorrespondingFields = function()
{
return self.origin == 'DDE' ? self.fieldsDDE : self.fieldsATT;
};
self.computed = function(group)
{
window.alert("Inside controller: computed");
if (!group) return "";
for (var str = "(", i = 0; i < group.rules.length; i++) {
i > 0 && (str += " <strong>" + group.operator + "</strong> ");
str += group.rules[i].group ?
self.computed(group.rules[i].group) :
group.rules[i].field + " " +
//htmlEntities(group.rules[i].condition)
group.rules[i].condition
+ " " + group.rules[i].data;
}
return str + ")";
};
$scope.$watch('filter', function (newValue)
{
//self.json = JSON.stringify(newValue, null, 2);
//TODO: do we need this??
//if( angular.isDefined( newValue ) )
//{
//window.alert("I am here again in watch!!!!" + JSON.stringify(newValue));
self.output = self.computed(newValue);
// self.ruleConditionOperators = self.getAllRuleConditionOperators();
// window.alert("I am HERE - end watch!!!!");
//}
}, true);
self.test = function()
{
window.alert(JSON.stringify( self.filter) );
};
}
]);
The screenshot:
At my first glance of the directive, I think you probably should change from:
var test = scope.$parent.fieldCodes;
scope.fields = scope.$parent.fields;
To:
//var test = scope.$parent.fieldCodes;
scope.fields = scope.$parent.fieldCodes;
I am trying to paginate a potentially very long list of divs. I have things working fine without the pagination however when I try to implement pagination (using this as a sort of template: http://plnkr.co/edit/81fPZxpnOQnIHQgp957q?p=preview) I receive an error: TypeError: cannot read property 'slice' of undefined . As far as I can tell this is an issue involving the $scope.data variable since I am calling slice on $scope.data . I am not sure how to resolve this and get it working. I will post the working version without pagination followed by the erroneous version with pagination. The only differences in the controller are from the line filteredTodos onward. I am calling fetchAllSamples() which populated $scope.data before any other work is done with pagination so I'm not sure why it would be undefined. All help is much appreciated.
Erroneous pagination html:
<div>
<div>
<div class="col-md-12">
<div style="border: 1px solid #000000">
<div ng-repeat="item in filteredTodos" style="margin-left: 14px">
{{item.name}}
<br> <span style="font-size: 20px">{{item.description}}</span>
<br>
<hr>
</div>
</div>
</div>
<pagination ng-model="currentPage" total-items="data.length" max-size="maxSize" boundary-links="true"> </pagination>
</div>
</div>
and correct non-paginated:
<div>
<div>
<div class="col-md-12">
<div style="border: 1px solid #000000">
<div ng-repeat="item in data" style="margin-left: 14px">
{{item.name}}
<br> <span style="font-size: 20px">{{item.description}}</span>
<br>
<hr>
</div>
</div>
</div>
</div>
</div>
which use the following controller:
app.controller('SamplesQueryController','$scope','$http', function($scope, $http) {
$scope.newSampleName = {
sampleName: ''
};
$scope.attributes = [{
name: '',
value: ''
}];
$scope.sampleCount = 0;
$scope.addAttribute = function() {
var attribute = {
name: '',
value: ''
};
$scope.attributes.push(attribute);
}
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.headerCount = 0;
$scope.headers = new Array("Id", "Name", "URL", "Description");
$scope.fetchAllSamples = function() {
$scope.response = null;
$scope.method = 'GET';
$scope.url = '/api/samples';
$http({
method: $scope.method,
url: $scope.url
}).then(function(response) {
$scope.data = response.data;
angular.forEach(response.data,function(value,key) {
$scope.sampleCount += 1;
});
},
function(response) {
$scope.data = response.data || "Request failed";
}
);
};
$scope.createSample = function() {
$scope.response = null;
$scope.method = 'POST';
$scope.url = '/api/samples';
$http({
method: $scope.method,
url: $scope.url,
data: JSON.stringify({
name: $scope.newSampleName.sampleName,
attributes: $scope.attributes
})
}).then(function(response) {
$scope.fetchAllSamples();
});
};
$scope.fetchAllSamples();
$scope.filteredTodos = [], $scope.currentPage = 1, $scope.numPerPage = 10, $scope.maxSize = 5;
$scope.$watch('currentPage + numPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage),
end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.data.slice(begin, end);
});
}]);
I am new to angularjs.
I want to implement https://angular-file-upload.appspot.com/ image upload functionality in tabs. When I put html elements which are required for image upload inside
<tabset><tab></tab></tabset> it doesn't work, but when I put it outside tabset it worked fine, but I want it inside <tabset><tab></tab></tabset>.
I am getting this error when I put html code inside <tabset></tabset>
Error: document.getElementById(...) is null
handleDynamicEditingOfScriptsAndHtml#http://localhost/angularAdmin/js/controllers/userForm.js:190:34
#http://localhost/angularAdmin/js/controllers/userForm.js:189:1
invoke#http://localhost/angularAdmin/vendor/angular/angular.js:4118:14
$ControllerProvider/this.$get</</<#http://localhost/angularAdmin/vendor/angular/angular.js:8356:11
nodeLinkFn/<#http://localhost/angularAdmin/vendor/angular/angular.js:7608:13
forEach#http://localhost/angularAdmin/vendor/angular/angular.js:347:11
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7607:11
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/</<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3762:11
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost/angularAdmin/vendor/angular/angular.js:14518:15
transitionTo/$state.transition<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3169:11
processQueue#http://localhost/angularAdmin/vendor/angular/angular.js:12984:27
scheduleProcessQueue/<#http://localhost/angularAdmin/vendor/angular/angular.js:13000:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost/angularAdmin/vendor/angular/angular.js:14200:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost/angularAdmin/vendor/angular/angular.js:14016:15
$RootScopeProvider/this.$get</Scope.prototype.$evalAsync/<#http://localhost/angularAdmin/vendor/angular/angular.js:14238:15
completeOutstandingRequest#http://localhost/angularAdmin/vendor/angular/angular.js:4842:7
Browser/self.defer/timeoutId<#http://localhost/angularAdmin/vendor/angular/angular.js:5215:7
<div ui-view="" class="fade-in ng-scope">
[1]: https://angular-file-upload.appspot.com/
app.js
'use strict';
angular.module('app', [
'ngFileUpload',
'toaster',
'LocalStorageModule',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.load',
'ui.jq',
'ui.validate',
'oc.lazyLoad',
'pascalprecht.translate'
]);
Controller
'use strict';
/* Controllers */
var version = '3.0.6';
// Form controller
app.controller('FormProfileCtrl', ['$scope', '$http', '$timeout', '$compile', '$upload', function ($scope, $http, $timeout, $compile, $upload) {
$scope.usingFlash = FileAPI && FileAPI.upload != null;
$scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);
$scope.changeAngularVersion = function () {
window.location.hash = $scope.angularVersion;
window.location.reload(true);
};
$scope.angularVersion = window.location.hash.length > 1 ? (window.location.hash.indexOf('/') === 1 ?
window.location.hash.substring(2) : window.location.hash.substring(1)) : '1.2.20';
$scope.$watch('files', function (files) {
console.log(files);
$scope.formUpload = false;
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
generateThumbAndUpload(file);
})(files[i]);
}
}
});
$scope.uploadPic = function (files) {
$scope.formUpload = true;
if (files != null) {
generateThumbAndUpload(files[0])
}
}
function generateThumbAndUpload(file) {
$scope.errorMsg = null;
$scope.generateThumb(file);
if ($scope.howToSend == 1) {
uploadUsing$upload(file);
} else if ($scope.howToSend == 2) {
uploadUsing$http(file);
} else {
uploadS3(file);
}
}
$scope.generateThumb = function (file) {
if (file != null) {
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
file.dataUrl = e.target.result;
});
}
});
}
}
}
function uploadUsing$upload(file) {
file.upload = $upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'my-header': 'my-header-value'
},
fields: {username: $scope.username},
file: file,
fileFormDataName: 'myFile',
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
file.upload.xhr(function (xhr) {
// xhr.upload.addEventListener('abort', function(){console.log('abort complete')}, false);
});
}
function uploadUsing$http(file) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
$timeout(function () {
file.upload = $upload.http({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: e.target.result
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}, 5000);
}
fileReader.readAsArrayBuffer(file);
}
function uploadS3(file) {
file.upload = $upload
.upload({
url: $scope.s3url,
method: 'POST',
fields: {
key: file.name,
AWSAccessKeyId: $scope.AWSAccessKeyId,
acl: $scope.acl,
policy: $scope.policy,
signature: $scope.signature,
"Content-Type": file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
filename: file.name
},
file: file,
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
storeS3UploadConfigInLocalStore();
}
$scope.generateSignature = function () {
$http.post('/s3sign?aws-secret-key=' + encodeURIComponent($scope.AWSSecretKey), $scope.jsonPolicy).
success(function (data) {
$scope.policy = data.policy;
$scope.signature = data.signature;
});
}
if (localStorage) {
$scope.s3url = localStorage.getItem("s3url");
$scope.AWSAccessKeyId = localStorage.getItem("AWSAccessKeyId");
$scope.acl = localStorage.getItem("acl");
$scope.success_action_redirect = localStorage.getItem("success_action_redirect");
$scope.policy = localStorage.getItem("policy");
$scope.signature = localStorage.getItem("signature");
}
$scope.success_action_redirect = $scope.success_action_redirect || window.location.protocol + "//" + window.location.host;
$scope.jsonPolicy = $scope.jsonPolicy || '{\n "expiration": "2020-01-01T00:00:00Z",\n "conditions": [\n {"bucket": "angular-file-upload"},\n ["starts-with", "$key", ""],\n {"acl": "private"},\n ["starts-with", "$Content-Type", ""],\n ["starts-with", "$filename", ""],\n ["content-length-range", 0, 524288000]\n ]\n}';
$scope.acl = $scope.acl || 'private';
function storeS3UploadConfigInLocalStore() {
if ($scope.howToSend == 3 && localStorage) {
localStorage.setItem("s3url", $scope.s3url);
localStorage.setItem("AWSAccessKeyId", $scope.AWSAccessKeyId);
localStorage.setItem("acl", $scope.acl);
localStorage.setItem("success_action_redirect", $scope.success_action_redirect);
localStorage.setItem("policy", $scope.policy);
localStorage.setItem("signature", $scope.signature);
}
}
(function handleDynamicEditingOfScriptsAndHtml($scope, $http) {
$scope.defaultHtml = document.getElementById('editArea').innerHTML.replace(/\t\t\t\t/g, '');
$scope.editHtml = (localStorage && localStorage.getItem("editHtml" + version)) || $scope.defaultHtml;
function htmlEdit(update) {
document.getElementById("editArea").innerHTML = $scope.editHtml;
$compile(document.getElementById("editArea"))($scope);
$scope.editHtml && localStorage && localStorage.setItem("editHtml" + version, $scope.editHtml);
if ($scope.editHtml != $scope.htmlEditor.getValue())
$scope.htmlEditor.setValue($scope.editHtml);
}
$scope.$watch("editHtml", htmlEdit);
$scope.htmlEditor = CodeMirror(document.getElementById('htmlEdit'), {
lineNumbers: true, indentUnit: 4,
mode: "htmlmixed"
});
$scope.htmlEditor.on('change', function () {
if ($scope.editHtml != $scope.htmlEditor.getValue()) {
$scope.editHtml = $scope.htmlEditor.getValue();
htmlEdit();
}
});
})($scope, $http);
$scope.confirm = function () {
return confirm('Are you sure? Your local changes will be lost.');
}
$scope.getReqParams = function () {
return $scope.generateErrorOnServer ? "?errorCode=" + $scope.serverErrorCode +
"&errorMessage=" + $scope.serverErrorMsg : "";
}
angular.element(window).bind("dragover", function (e) {
e.preventDefault();
});
angular.element(window).bind("drop", function (e) {
e.preventDefault();
});
}])
;
View
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">Edit User</h1>
</div>
<div class="wrapper-md">
<!-- breadcrumb -->
<div>
<ul class="breadcrumb bg-white b-a">
<li><a ui-sref="app.dashboard"><i class="fa fa-home"></i> Dashboard</a></li>
<li class="active">Edit User</li>
</ul>
</div>
<!-- / breadcrumb -->
<div class="col-lg-12">
<div class="wrapper-md" ng-controller="FormProfileCtrl">
<form name="userForm" class="form-validation">
<tabset justified="true" class="tab-container">
<tab heading="Personal Information">
<div class="panel-body">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" ng-model="user.vName" >
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" ng-model="user.vEmail">
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vPhone" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vAddress" ></textarea>
</div>
<div class="form-group pull-in clearfix">
<div class="col-sm-6">
<label>Enter password</label>
<input type="password" class="form-control" name="vPassword" ng-model="vPassword" >
</div>
<div class="col-sm-6">
<label>Confirm password</label>
<input type="password" class="form-control" name="confirm_password" required ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' ">
<span ng-show='form.confirm_password.$error.validator'>Passwords do not match!</span>
</div>
</div>
</div>
</tab>
<tab heading="Company Information">
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" ng-model="user.vCompanyName" >
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vCompanyPhone" >
</div>
<div class="form-group">
<label>Designation</label>
<input type="text" class="form-control" ng-model="user.vDesignation" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vCompanyAddress" ></textarea>
</div>
</tab>
</tabset>
<!-- I want -->
<div class="upload-div">
<div class="upload-buttons">
<div id="editArea">
<fieldset><legend>Upload right away</legend>
<div ng-file-drop ng-file-select ng-model="files" ng-model-rejected="rejFiles"
drag-over-class="{accept:'dragover', reject:'dragover-err', delay:100}" class="drop-box"
ng-multiple="true" allow-dir="true" ng-accept="'image/*,application/pdf'">
Drop Images or PDFs<div>or click to select</div>
</div>
<div ng-no-file-drop class="drop-box">File Farg&Drop not supported on your browser</div>
</fieldset>
<br/>
</div>
</div>
<ul ng-show="rejFiles.length > 0" class="response">
<li class="sel-file" ng-repeat="f in rejFiles">
Rejected file: {{f.name}} - size: {{f.size}}B - type: {{f.type}}
</li>
</ul>
<ul ng-show="files.length > 0" class="response">
<li class="sel-file" ng-repeat="f in files">
<img ng-show="f.dataUrl" ng-src="{{f.dataUrl}}" class="thumb">
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%">{{f.progress}}%</div>
</span>
<button class="button" ng-click="f.upload.abort();
f.upload.aborted = true"
ng-show="f.upload != null && f.progress < 100 && !f.upload.aborted">Abort</button>
{{f.name}} - size: {{f.size}}B - type: {{f.type}}
<a ng-show="f.result" href="javascript:void(0)" ng-click="f.showDetail = !f.showDetail">details</a>
<div ng-show="f.showDetail">
<br/>
<div data-ng-show="f.result.result == null">{{f.result}}</div>
<ul>
<li ng-repeat="item in f.result.result">
<div data-ng-show="item.name">file name: {{item.name}}</div>
<div data-ng-show="item.fieldName">name: {{item.fieldName}}</div>
<div data-ng-show="item.size">size on the serve: {{item.size}}</div>
<div data-ng-show="item.value">value: {{item.value}}</div>
</li>
</ul>
<div data-ng-show="f.result.requestHeaders" class="reqh">request headers: {{f.result.requestHeaders}}</div>
</div>
</li>
</ul>
<br/>
<div class="err" ng-show="errorMsg != null">{{errorMsg}}</div>
</div>
<input type="hidden" class="form-control" ng-model="user.iUserID">
<input type="submit" class="btn btn-success" ng-click="postForm(user)">
</form>
</div>
</div>
I had a similar problem with ng-file-upload and tabset. Here is how I solved it.
In my controller, I created a new object:
$scope.tab_data = {}
and then changed the watch to
$scope.$watch 'tab_data.files', ->
$scope.upload $scope.tab_data.files
Lastly, I updated the ng-model in my html tag.
<div ngf-drop ngf-select ng-model="tab_data.files" class="drop-box" ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true" ngf-accept="'.jpg,.png,.pdf'" class="drop-box">
<div ngf-drop-available >Drop Images here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
<div>click to select</div>
</div>
Of course my solution is in coffeescript...sorry if that is an issue but it should be easy for you to convert back to js.
I have posted earlier this post with the choice of not providing all my code. But now im stuck since with the same problem so I give it a change with providing all my code.
I know its not easy to debug when the code is huge so I will try to explain precisely the problem.
Actually the problem is described in my precedent post so please read it and look at the code that is a simplification of this one.
But basically the problem is : I want to access $scope.data.comments from the $scope.deleteComment() function
As you see the code below you will notice that I have to add ng-controller="CommentController" twice for this to work.
If someone could explain why.. that would be great but I guess that is another question.
Thanks in advance for your help.
MAIN HTML
<div ng-init="loadComments('${params.username}', '${params.urlname}' )" ng-controller="CommentController">
<div ng-repeat="comments in data.comments" >
<div sdcomment param="comments" ></div>
</div>
</div>
APP
var soundshareApp = angular.module('soundshareApp', ['ngCookies']);
DIRECTIVES
soundshareApp.directive('sdcomment', ['$cookies', function($cookies){
var discussionId = null;
var found = false;
var username = $cookies.soundshare_username;
return {
restrict:'A',
scope: {
commentData: '=param'
},
templateUrl: '/js/views/comment/templates/commentList.html',
link : function(scope, element, attrs, controller) {
scope.$watch(element.children(), function(){
var children = element.children();
for(var i=0; i<children.length; i++){
if(children[i].nodeType !== 8){ //pas un commentaire <!-- -->
if( !found ){
found = true;
discussionId == scope.commentData.discussionId
}else if(found && discussionId == scope.commentData.discussionId){
angular.element(children[i]).removeClass('message-content');
angular.element(children[i]).addClass('answer-message-content');
}
if(found && discussionId != scope.commentData.discussionId){
discussionId = scope.commentData.discussionId
}
if(username == scope.commentData.username){
element.parent().bind('mouseover', function() {
// $(".delete-comment-button").show()
element.parent().find("span.delete-comment-button:first").attr('style', 'display: block !important');
});
element.parent().bind('mouseleave', function() {
element.parent().find("span.delete-comment-button:first").attr('style', 'none: block !important');
});
}
}
}
});
}
}
}]);
TEMPLATE
<div class="message-wrapper" ng-controller="CommentController">
<div class='message-content' ng-click="state.show = !state.show; setUsername(commentData.username)">
<img class='message-vignette' ng-src='{{commentData.avatarUrl}}'/>
<div class='message-username'>{{commentData.username}}</div>
<div class='project-message'>{{commentData.comment}}</div>
<div class='message-date'>{{commentData.dateCreated | date:'dd.MM.yyyy # hh:mm:ss' }}</div>
<div class="clearfix"></div>
</div>
<div ng-repeat="answer in answers" class="answer-message-content" >
<div class='message-content' ng-click="state.show = !state.show">
<img class='message-vignette' ng-src='{{answer.avatarUrl}}'/>
<div class='message-username'>{{answer.username}}</div>
<div class='project-message'> {{answer.comment}}</div>
<div class='message-date'>{{answer.dateCreated | date:'MM/dd/yyyy # h:mma' }}</div>
<div class="clearfix"></div>
</div>
</div>
<div class="add-comment-content show-hide" ng-show="state.show" >
<img class='message-vignette answer-message-vignette' ng-src='{{commentData.currentUserAvatarUrl}}'>
<div class="">
<form ng-submit="addComment(commentData)" id="commentForm-{{commentData.projectId}}">
<input id="input-comment-{{commentData.projectId}}" type="text" maxlength="" autofocus="autofocus" name="comment" placeholder="Write a comment..." ng-model="commentData.msg">
<input type="hidden" name="discussionId" value="{{commentData.discussionId}}" >
<input type="hidden" name="projectId" value="{{commentData.projectId}}" >
</form>
</div>
</div>
<span ng-click="deleteComment(commentData)" class="btn btn-default btn-xs delete-comment-button"><i class="icon-trash"></i></span>
</div>
CONTROLLER
'use strict';
soundshareApp.controller('CommentController', function($scope, $http) {
$scope.data = { comments : [] }
$scope.answers = [];
$scope.state = {}
$scope.project = { id : [] }
$scope.username = null;
$scope.loadComments = function(userName, urlName){
$http({
url: '/comment/by_project_id',
method: "GET",
params:
{
username: userName,
urlname: urlName
}
}).success(function(data) {
$scope.data.comments = data;
console.log($scope.data.comments);//WORKING
});;
}
$scope.addComment = function(commentData){
if("undefined" != commentData.msg){
commentData.msg = "#" + $scope.username + ": " + commentData.msg;
$http({
method : "POST",
url : "/comment/addAnswer",
params:
{
comment: commentData.msg,
discussionId: commentData.discussionId,
projectId:commentData.projectId
}
}).success(function(data){
$scope.answers.push(data);
$('.show-hide').hide();
$scope.commentData.msg = '';
});
}
}
$scope.setUsername = function(username){
$scope.username = username;
}
$scope.deleteComment = function ( comment ) {
console.log($scope.data.comments);//NOT WORKING
};
});