I'm sorry but I got some troubles with AngularJs.
I have to get an image from S3 bucket and I want to inject it inside directive but I'm lost to how make it.
Here is what I made but, obviously it does not work and I'm pretty sure I'm in the wrong way.
No java code here because I know I properly get the image from S3 bucket.
.directive('logoApp', function(){
return {
restrict: 'A',
template: "<div class='logo' style='background-image:
url(data:image/png;base64,<image I want to inject>);'></div>",
scope: {
logoApp: "="
}
}
})
.service('StartService', function($scope, $http) {
$scope.logo = {
getFileFromS3 : function () {
$http({
method: 'GET',
url: '/**/{[path:[^\\.]*}'
}).then(function(data) {
console.log(data);
$rootScope.err({
title: 'Internal erro',
code: '500',
message: 'dialog_confirm_download_error'
});
});
}
}
})
Thank you
EDITED
I tried something like this and replace .service by .factory
.factory('StartService', function($http, $rootScope) {
return {
getFileFromS3: function () {
return $http({
method: 'GET',
url: '/<something>'
}).then(function (data) {
console.log("data" + JSON.stringify(data.data));
$rootScope.err({
title: 'Erreur Interne',
code: '500',
message: 'dialog_confirm_download_error'
});
});
}
}
})
And I can see I get my image in "data.data" but unfortunately, this part doesn't display my logo and let '{}' empty
.directive('logoApp', ['StartService', function(startService){
return {
restrict: 'E',
replace: true,
template: "<p>{{ logo }}</p>",
controller: function($scope) {
},
link: function($scope) {
console.log('start service ' + JSON.stringify(startService.getFileFromS3()));
$scope.logo = startService.getFileFromS3();
}
}
I believe this may be what you're looking for. I have changed the restrict to 'E' so that it is an element level directive and also added replace=true which will replace your directive element with the template from the directive.
Using the directive in your html would be like so:
<logo-app></logo-app>
Hope this helps.
.directive('logoApp', function(){
return {
restrict: 'E',
replace: true,
template: "<div class='logo' style='background-image:
url(data:image/png;base64,{{vm.imageData}});'></div>",
controller: ['StartService', function(StartService) {
var vm = this;
vm.imageData;
StartService.getFileFromS3()
.then(result => vm.imageData = result)
.catch(error => console.error(error));
}],
controllerAs: 'vm'
}
})
Please check the plunkr example for a live example using the code above.
Related
I'm trying to make GET request the first time I load an AngularJS (1.6) directive and show its result in the directive's template.
What I am trying so far is the following:
JS:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
attrs: {
foo : String,
onResponse : function(response){
this.foo = response.data;
}
},
templateUrl: 'templates/my-directive.html',
compile: function(scope, element, attrs) {
$http({
method: 'GET',
url: 'my/url'
}).then(
attrs.onResponse
);
}
}
}]);
the HTML template:
<div id="my-directive">
foo: <span>attrs.foo</span>
</div>
Is there a way to do this properly?
Thanks in advance!
Well, I managed to do what I wanted by adding a controller:
app.directive("myDirective", ['$http', function($http) {
return {
restrict: 'AE',
controller: "myDirectiveController",
templateUrl: 'templates/my-directive.html'
}
}]);
where
app.controller('myDirectiveController', function ($scope, $http) {
$scope.foo;
$scope.onResponse = function(response){
$scope.foo= response.data;
}
$http({
method: 'GET',
url: 'my/url'
}).then(
$scope.onResponse
);
});
and the template looks like this:
<div id="my-directive">
foo: <span>{{foo}}</span>
</div>
Probably this is not the proper way to do it but it works.. Any suggestions are welcome!
This is a part of my codes
Object_Angular.directive("ntgChangeScanInnerHtmlWorkshop", ["$timeout", function($timeout){ ...
But I need to also get access to $http since I want to load things from my API. How can I do this?
What I have is a display of _ids in a <p></p>. Let say I have <p>{{collections._id}}</p>. I want that <p></p> to display the name field (collections.String_Name) not the _id. So I think to take the inner HTML of the <p>{{collections._id}}</p> after the value loads and then GET the String_Name from the API via { _id: innerHTMLValueOfP } then in .success I do set back the inner value with result.String_Name. Hence I need to have $http and $timeout in my directive to achieve this.
Example of using $http in directive
app.directive('myTag', ['$http', function($http) {
return {
restrict: 'E',
transclude: true,
replace: true,
scope:{
src:"="
},
controller:function($scope){
console.info("enter directive controller");
$scope.gallery = [];
console.log($scope.src);
$http({method: 'GET', url:$scope.src}).then(function (result) {
console.log(result);
}, function (result) {
alert("Error: No data returned");
});
}
}
}]);
or
app.directive('example', function( $http){
return {
restrict:'E',
link: function($scope,$element,$timeout){
$http.post('/example', {
data
}).success(function(data){
}).error(function(data){});
}
});
I'm fairly new to Angular, and I'm trying to update one of my controller's variables from a directive, but it won't seem to work. The variable is populated in the directive, and when I log it there it's fine. Then when I try to log the variable from the controller; it logs fine at first, then it's "undefined".
I have no idea why this is happening. Help :(
Directive
app.directive('reportFilter', function() {
return {
restrict: 'E',
scope: {},
controller: 'MainController',
templateUrl: 'js/directives/reportFilter.html',
link: function(scope, element, attrs) {
scope.updateTable = function(selectedOffer,startDate,endDate) {
var offer='offer:'+selectedOffer.offer_id;
$.ajax({
type: 'POST',
url: 'daily_summary.php',
data: {
'offer': selectedOffer.offer_id
},
dataType: 'json',
cache: false,
success: function(response) {
scope.myvariable=response;
scope.getData();
console.log(scope.myvariable);
scope.$apply();
}
});
}
}
}
});
Controller
app.controller('MainController', ['$scope', 'service', 'Offerservice','$attrs', function($scope, service,Offerservice) {
$scope.getData= function () {
console.log($scope.myvariable);
return $scope.myvariable;
};
}]);
I am trying to pass two different parameter to isolated scope inside directive.When I log out values in console then for collapse I am getting true but for infoCard I am getting false value.My question is why I am getting false value for infoCard Thanks in advance.Here is my directive.
<display-info user="user" collapse="true" infoCard="true"></display-
info>
In my controller i am receiving the parameter,
angular.module('myApp').directive('displayInfo', function() {
return {
templateUrl: "displayInfo.html",
restrict: "EA",
scope: {
user: '=',
initialCollapse:'#collapse',
showInfo:'#infoCard'
},
controller: function($scope) {
$scope.collapse = ($scope.initialCollapse === 'true');
$scope.infoCard = ($scope.showInfo === 'true');
console.log("collapse---->",$scope.collapse);
console.log("displyInfo---->",$scope.infoCard);
}
}
});
Here is plunker link https://plnkr.co/edit/Gng7e4RRVvg8wPOnqQrk?p=preview
camel case convention have problem in directive
Try this.
<display-info user="user" collapse="true" test="true"></display-info>
angular.module('myApp').directive('displayInfo', function() {
return {
templateUrl: "displayInfo.html",
restrict: "EA",
scope: {
user: '=',
initialCollapse:'#collapse',
showInfo:'#test'
},
controller: function($scope) {
$scope.collapse = ($scope.initialCollapse === 'true');
$scope.infoCard = ($scope.showInfo === 'true');
console.log("collapse---->",$scope.collapse);
console.log("displyInfo---->",$scope.infoCard);
}
}
});
I'm trying to create a directive to load select items(from server) for the lists that I need using a Key for each list, but it seams that model is bound before the items get a chance to load, and the desired item is not get selected, any suggestion?
Services:
arsinServices.factory('GeneralProperties', ['$resource', function ($resource) {
return $resource('/api/GeneralProperties/');
}]);
Directive:
directives.directive('ngarGpSelect', ['GeneralProperties',
function (GeneralProperties) {
return {
restrict: 'E',
replace: true,
scope: {
ngModel: '='
},
controller: function ($scope, $attrs, GeneralProperties) {
$scope.gpItems = GeneralProperties.query({ key: $attrs.gpkey });
},
templateUrl: '/templates/gp-select.html',
require: 'ngModel',
}
}]);
Template:
<select ng-options="gp.Index as gp.Name for gp in gpItems"></select>
Contoller:
arsinControllers.controller('RequestEditCtrl', ['$scope', 'request',
function ($scope, request) {
$scope.request = request;
}
View:
<ngar-gp-select gpKey="RequestType" ng-model="request.RequestTypeIndex"/>
Update
Here is a fiddle thanks to #Nix.
Update 2:
If I replace the line which set gpItems in directive controller whith something like this:
$scope.gpItems = [{ Index: 1, Name: 'option1' }, { Index: 2, Name: 'option2' }, { Index: 3, Name: 'option3' }];
It will work as expected, and the item get selected.
You have yet to really show an "issue"... I dont understand what you are trying to do but if you initialize $scope.request in the fiddle Nick will be selected.
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.request = {
RequestTypeIndex: 1
}
$scope.RequestType = 1
}
Then in your directive you need to use the promise(although your example should work):
function (GeneralProperties) {
return {
restrict: 'E',
replace: true,
scope: {
ngModel: '='
},
controller: function ($scope, $attrs, GeneralProperties) {
GeneralProperties.query({ key: $attrs.gpkey }).then(function(data){
$scope.gpItems = data
}, function(error){
alert(error);
})
},
templateUrl: '/templates/gp-select.html',
require: 'ngModel',
}
}]);
Utilize a callback from the query:
GeneralProperties.query({ key: $attrs.gpkey }, function(data) {
$scope.gpItems = data;
});
Finally I located the problem, it was because of items from my service. the Index property was of type string instead of int, I changed the type in my server side interface and it worked. I have had found similar cases in SO mentioning this but I overlooked them. I hope it will help someone else.