angular directive load after got variables - javascript

I have an angular directive that loads data from service,
BUT
it loads the data with a variable he go from a controller that it was loaded as well from a service.
code:
directive:
app.directive("posts", ['Posts', function(Posts) {
return {
restrict: 'E',
template: '' +
'<div ng-repeat="post in posts"></div>',
scope: {
showLoading: '&',
hideLoading: '&',
spot: '#'
},
controller: ['$scope', function ($scope) {
}],
link: function(scope, element, attrs) {
$scope.load = function () {
Posts.loadPostsBySpot(scope.spot)
};
}
};
}]);
Controller
app.controller('spotPageController', ['$scope', 'Spots', function ($scope, $Spots) {
doit = function () {
Spots.getSpot($)
.success(function (data) {
$scope.spotId = data.data;
console.log($scope.spot);
}).error(function (data) {
console.log('error');
});
};
}]);
html inside
<posts spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>
but when the directive is loaded the "spot" is not yet set,
so how do I make the directive load only after the spot is set.

Use ng-if.
<posts ng-if="spotId" spot="{{spotId}}" showLoading="showLoading()" hideLoading="hideLoading()"></posts>
This element will be rendered only after the spotId is initialized. Therefore, your directive will not be called before that.
If you want to encapsulate this behavior in directive, you should watch for changes of the scopeId. See the fiddle.

Related

Using service inside directive?

I am learning how to create custom directives.
My service looks like that:
myApp.service('myService',function(){
this.myFunction=function(myParam){
// do something
}
});
Here is my directive:
myApp.directive('myDirective',function(myService){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="myService.myFunction(param)">Do action</button>',
}
});
In HTML, when I use <my-directive my-param="something"></my-directive> it properly renders as a button. However when I click it, myService.myFunction, doesn't get executed.
I suppose I am doing something wrong. Can someone give me a direction?
I guess this has something to do with the directive's scope.
The service wont be available directly inside the template. You'll have to use a function attached to the directive's scope and call the service function from within this function.
myApp.directive('myDirective',function(myService){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="callService(param)">Do action</button>',
link: function(scope, element, attrs) {
scope.callService = function() {
myService.myFunction();
}
}
}
});
It doesn't work because in your example a directive doesn't actually know what is myService. You have to explicitly inject it e.g.:
myApp.directive('myDirective', ['myService', function(myService){ ... }]);
See also this question or this question.
You should use a controller to do all DOM-modifications.
See this plunkr: https://plnkr.co/edit/HbfD1EzS0av5BG6NgtIv?p=preview
.directive('myFirstDirective', [function() {
return {
'restrict': 'E',
'controller': 'MyFirstController',
'controllerAs': 'myFirstCtrl',
'template': '<h1>First directive</h1><input type="text" ng-model="myFirstCtrl.value">'
};
}
You can inject the service in the controller and then call that function inside your template:
Inject myService into controller:
myApp.controller("ctrl", function($scope, myService) {
$scope.doService = function(myParam) {
return myService.myFunction(myParam);
};
});
Call doService method of the controller inside your template:
myApp.directive('myDirective',function(){
return {
restrict: 'E',
scope: {
param: '=myParam',
},
template: '<button ng-click="doService(param)">Do action</button>',
}
});

How to pass data from a custom angular element to the controller?

I have a controller and element directive:
ngModule
.controller('summaryCtrl', [ '$scope', '$http', function($scope, $http){
$scope.loaded = false;
$http
.get('some/item/'+itemId) //how do I get this itemId
.success(function(data){
$scope.data = data;
$scope.loaded = true;
})
.error(function(data){
//TODO
});
}])
.directive('cpSummary', function(){
return {restrict: 'E', templateUrl: 'some/path.html'};
});
and I want to use the directive something like this:
<cp-summary item-id="{id}" ng-controller="summaryCtrl"></cp-summary>
the item-id attribute get's set by the parent controller that is rendering the cp-summary elements in a ng-repeat. So I'd just like to know if it's possible to get the item-id attribute value inside the summaryCtrl.
You should use a controller for your directive. and then you can pass the item-id to the directive controller and do the stuff.
app.directive('cpSummary', function(){
return {
restrict: 'E',
templateUrl: 'some/path.html',
scope: {
item_id: '=itemId'
},
controller: ['$scope','$http',function($scope,$http) {
$http
.get('some/item/'+$scope.item_id)
.success(function(data){
$scope.data = data;
$scope.loaded = true;
})
.error(function(data){
//TODO
});
}]
};
});
As you wanted to pass id to you directive then you should include that variable inside directive isolated scope. It should be {{id}} instead of {id} & then use # inside your directive. # is for one way binding. Also assign the controller from directive.
Markup
<cp-summary item-id="{{id}}"></cp-summary>
Directive
.directive('cpSummary', function(){
return {
restrict: 'E',
templateUrl: 'some/path.html',
scope: {
item_id: '#itemId'
},
controller: 'summaryCtrl'
};
});
var app = angular.module("App", []);
app.directive("myDirective", function() {
var itemFunction = function(scope, element, attributes) {
scope.item-id= attributes["myDirective"];
};
return {
restrict: "A",
template: "<p></p>",
link: itemFunction
};
});

Passing a controller to a directive in angularJS. Gives undefined error

I am working to add modals to my directives using ui-bootstrap and did so fine on the previous directive. I don't believe I am doing anything differently in this one but I get the ReferenceError: milestoneController is not defined when I run the edit() function from within the directive.
milestone.html (this is the template HTML for the directive below):
<div ng-controller = "milestoneController"></div>
milestone directive:
angular.module('ireg').directive('milestone', function (milestoneFactory,$modal) {
return {
restrict:'E',
scope: {
objectid:'#objectid'
},
templateUrl: '/ireg/components/milestone/milestone.html',
link: function ($scope, element, attrs) {
$scope.edit = function(data) {
milestoneController.editMilestoneDialog(data);
};
}
}
});
angular.module('ireg').controller('milestoneController', function ($scope, $modal){
$scope.editMilestonesDialog = function (objectid) {
//fun
}
});
EDIT: I allso felt I should mention that the milestone directive is repeated in a ng-repeat loop. Thanks!
ok you're going to want to use a transcluded scope in your directive to pass a controller function to the directive. Your directive now becomes:
angular.module('ireg').directive('milestone', function (milestoneFactory,$modal) {
return {
restrict:'E',
scope: {
objectid:'#objectid',
editMilestoneDialog:'&'
},
templateUrl: '/ireg/components/milestone/milestone.html',
link: function ($scope, element, attrs) {
$scope.edit = function(data) {
$scope.editMilestoneDialog(data);
};
}
}
and your markup becomes:
<milestone edit-milestone-dialog="editMilestoneDialog"></milestone>

How to pass a collection to a directive in angular.js?

Please forgive my lack of understanding.
I pass the name of a collection to my directive:
<ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul>
The directive is defined:
app.directive('tagIt', function (){
return {
restrict: 'A',
link: function(scope,elem, attr) {
elem.tagit();
console.log(attr.tagSrc); //the name of my collection, but how do I access it?
}
}
});
How do I access my collection from the directive and make sure my directive is called when the collection is populated? Here is how preview_data.preview.extract.keywords gets populated.
app.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
console.log('config');
$routeProvider.when("/", {
templateUrl: "/templates/addItem.html",
controller: "AddItemController",
resolve: {
loadData: addItemCtrl.loadData
}
});
});
var addItemCtrl=app.controller("AddItemController", function ($scope, $route, $sce, Preview) {
var title = decodeURIComponent($route.current.params.title);
var ua = decodeURIComponent($route.current.params.ua);
var uri = decodeURIComponent($route.current.params.uri);
$scope.preview_data = {
uri: uri,
title: title,
ua: ua
}
//pass parameters to web preview API
Preview.get(uri, ua, title).then(function (data) {
$scope.preview_data.preview = data;
if (data.embed.html) {
$scope.preview_data.preview.embed.html = $sce.trustAsHtml(data.embed.html);
}
}, function (data) {
alert('Error: no data returned')
});
});
You need to set the variable in the directive scope and set the template to iterate between the tags:
template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
scope : {
tagSrc : '='
},
And will became this:
app.directive('tagIt', function (){
return {
restrict: 'A',
template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>',
scope : {
tagSrc : '='
},
link: function(scope,elem, attr) {
console.log(attr.tagSrc);
}
}
});
the '=' attribute will tells to angular to use a tw way binding with the array passed in the directive declaration in the HTML.
Here is a plunker with a working example.
And here is a good arcticle explaning the directive's attributes and life cycle.
I hope it helps.
[EDIT]
If you want just iterate the array, without creating some different behavior in the list items, you can just simply use the ng-repeat directive:
<ul>
<li data-ng-repeat="tag in tags">{{tag.name}}</li>
<ul>

Partial View does not compile properly in angular

// Code goes here
var mymodule = angular.module('myapp', []);
mymodule.controller('mycontroller', function ($scope) {
});
mymodule.directive('pvTempUrl',
function ($http, $compile, $log, $templateCache) {
$log.info("Directive Called");
return {
restrict: 'A',
replace: true,
compile: function (telement, tattr, transclude) {
var templateloader = $http.get(tattr.pvTempUrl, { cache: $templateCache }).
success(function (data) {
$log.info("Success-" + data);
telement.html(data);
}).
error(function (data, status) {
$log.warn("Error occured - " + data + " status-" + status);
});
return function (scope, element, attr) {
templateloader.then(function () {
var compiledHtm = ($compile(telement.html())(scope)).html();
$log.info("compiled html-" + compiledHtm);
element.html(compiledHtm);
});
};
}
};
});
I have a partial page trying to compile the page is working just showing the template as such.
Plunkr is avaliable here
http://plnkr.co/edit/U85rmXhuQGKx5pkzUu99?p=preview
Issue found i was binding the html not the compiled object resolved the issue like below
// Code goes here
var mymodule = angular.module('myapp', []);
mymodule.controller('mycontroller', function ($scope) {
});
mymodule.directive('pvTempUrl',
function ($http, $compile, $log, $templateCache) {
$log.info("Directive Called");
return {
restrict: 'A',
replace: true,
compile: function (telement, tattr, transclude) {
var templateloader = $http.get(tattr.pvTempUrl, { cache: $templateCache }).
success(function (data) {
$log.info("Success-" + data);
telement.html(data);
}).
error(function (data, status) {
$log.warn("Error occured - " + data + " status-" + status);
});
return function (scope, element, attr) {
templateloader.then(function () {
var compiledHtm = ($compile(telement.html())(scope));
$log.info("compiled html-" + compiledHtm);
//element.html(compiledHtm);
element.replaceWith(compiledHtm);
$log.info(element.html());
});
};
}
};
});
I haven't seen anyone try to load a template this way before. The proper Angular ways of loading a template are the following:
Using ng-view to load a predefined template file.
Building your own custom directive.
I feel like you are attempting to do the second method. The following code sample is an example of how to do that.
angular.module("myapp")
.directive('buttonsRadio', function() {
return {
restrict: 'E',
scope: false,
controller: function($scope){
//Any logic required for directive to work.
},
templateUrl: 'template.html'
};
})
In your template.html file you would have your template you wish to load.
For much more detail and examples on how to build your own custom directive elements, see the section Writing Directives (long version) in the Angular docs.
UPDATE: Edited to show example of templateUrl.

Categories