I have 2 directives both placed on a single div. But only the content of the first directive is placed inside the div. Is it possible to let 2 directives change the html of this div?
-HTML
<div messages messageControls/>
-Messages Directive
(function() {
"use strict";
define(function() {
messages = [
function() {
return {
priority: 1,
restrict: 'A',
templateUrl: '../../messages.html', (<p>hello world</p>)
scope: {
},
link: function(scope) {}
};
}
];
return messages;
});
}).call(this);
-MessageControls Directive
(function() {
"use strict";
define(function() {
messageControls = [
function() {
return {
priority: 2,
restrict: 'A',
templateUrl: '../../messageControls.html', (<p>delete message</p>)
scope: {
},
link: function(scope) {}
};
}
];
return messageControls;
});
}).call(this);
When I only add one directive, it works. But when I add the second one I get the following angular error:"Multiple directives asking for template on
Related
I have a directive which loads a image data template.
The problem is that It doesn't update the image date after the service which retrieve the img information is called.
This is my code:
Controller method:
$scope.watchImage = function(file_id){
FileService.getFile(file_id)
.then(
function(data){
if(data.file){
$scope.img = data.file;
console.log('Service called');
}
}
);
}
Directive:
app.directive('imageDetails', function() {
return {
scope: {
img: '='
},
restrict: 'E',
link: function($scope, element, attrs){
$scope.$watch(function() {
return $scope.img;
}, function() {
console.log($scope.img);
});
},
template: 'IMG: {img}'
};
});
HTML:
<div class="ui container">
<h2 class="ui dividing header">Images</h2>
</div>
<div ng-view></div>
<image-details img="img"></image-details>
</div>
Log result:
undefined
Service called
Any idea how to solve it ?
Thanks!
First of all, thank you to everyone for your replies. All of them help me in the solution.
Finally this is my working code.
Directive:
app.directive('imageDetails', function() {
return {
scope: {
img: '='
},
restrict: 'E',
template: 'IMG: {{img}}'
};
});
And I added the directive to my template (I was adding it outside ngview).
you have some mistake in template and in link function.
var app = angular.module('myApp', []);
app.controller('mainCtrl', function ($scope) {
$scope.img = {id: 1, title: "avatar.jpeg", slug: "avatar.jpeg", filesize: 24875, created_at: "2016-03-10 11:44:59"};
})
app.directive('imageDetails', function() {
return {
scope: {
img: '='
},
restrict: 'E',
link: function(scope, element, attrs){
scope.$evalAsync(function() {
return scope.img;
});
},
template: 'IMG: {{img}}'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="mainCtrl">
<image-details img="img"></image-details>
</div>
I think your directive should be Like :
app.directive('imageDetails', function() {
return {
scope: {
img: '='
},
restrict: 'E',
link: function(scope, element, attrs){
scope.$watch('img',function(image) {
return image;
}, function() {
console.log(image);
});
},
template: 'IMG: {img}'
};
});
First of all use a controller instead of link function because you don't need that. Link function is deprecated for simple components like this in angular 1.5.
Then, for using $watch, you need to specify what variable you want to watch, and only after what to do when it's change.
$watch('varToWatch', function(newValue) {...});
That said, if you use a controller instead of the link function, you probably use also a "Controller as" syntax. When you use it, you need to specify the "view name" of the variable you want to watch. For example:
app.directive('imageDetails', function() {
return {
scope: {
img: '='
},
restrict: 'E',
controllerAs: '$ctrl',
controller: function($scope){
$scope.$watch('$ctrl.img', function(newVal) {
console.log(newVal);
// if you want you can assign new value to your variable
// $scope.img = newVal;
});
},
template: 'IMG: {img}'
};
});
Try that and tell me if it's works for you ;)
This is a clear case of when the scope is affected outside the module. For those cases the lifecycle will not do the digest of the scope as you will expect.
You have to manually $digest or $apply when you want to notify your app that the scope have changed inside your directive
I have an element directive (e-dir) and an attribute directive (a-dir) on the same element:
<e-dir a-dir attr="msg"></e-dir>
I pass msg into e-dir's isolate scope via the attr attribute:
app.directive('eDir', function eDir($timeout) {
return {
restrict: 'E',
scope: {
attr: '='
}
};
});
In this way, msg is bound (two-ways) with $scope.attr (in EDirCtrl) or scope.attr (in e-dir's link function).
Is there a simple way I can achieve the same two-way data-binding inside a-dir's directive? Or would you recommend another, simpler approach?
The closest thing I've been able to come up with is to set eDirCtrl.attr = $scope.attr; inside e-dir's controller (EDirCtrl):
app.directive('eDir', function eDir($timeout) {
return {
restrict: 'E',
scope: {
attr: '='
},
controller: function EDirCtrl($scope) {
var eDirCtrl = this;
eDirCtrl.attr = $scope.attr;
},
controllerAs: 'eDirCtrl'
};
});
Then, have a-dir require e-dir, and access attr via e-dir's controller (eDirCtrl.attr):
app.directive('aDir', function aDir($timeout) {
return {
restrict: 'A',
require: 'eDir',
link: linkFn
};
function linkFn(scope, element, attrs, eDirCtrl) {
eDirCtrl.attr = 'eDirCtrl.attr';
}
});
But, it's not bound two-ways. As you can see this code snippet:
var app = angular.module('app', []);
app.controller('Ctrl', function Ctrl($scope) {
$scope.msg = 'initial message';
})
app.directive('eDir', function eDir($timeout) {
return {
restrict: 'E',
scope: {
attr: '='
},
template: '<div>$scope.attr: {{attr}}</div>'+
'<div>eDirCtrl.attr: {{eDirCtrl.attr}}</div>',
controller: function EDirCtrl($scope) {
var eDirCtrl = this;
eDirCtrl.attr = $scope.attr;
$timeout(function() {
$scope.attr = 'changing $scope.attr also changes msg';
}, 2000);
},
controllerAs: 'eDirCtrl'
};
});
app.directive('aDir', function aDir($timeout) {
return {
restrict: 'A',
require: 'eDir',
link: linkFn
};
function linkFn(scope, element, attrs, eDirCtrl) {
$timeout(function() {
eDirCtrl.attr = 'changing eDirCtrl.attr does not effect $scope.attr or msg';
}, 4000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
msg: <input type="text" ng-model="msg"><br>
<e-dir a-dir attr="msg"></e-dir>
</div>
The reason the two-way binding isn't working is that attr is being bound to a string rather than an object. In JavaScript, primitives (booleans, numbers, strings) are immutable, so when you change one, the previous instance is discarded and a new one is used. This breaks Angular's two-way binding and any changes to scope.msg are not propagated through attr into the directive.
You can get this to work as expected by setting msg on an object e.g. scope.test.msg and binding attr to test (the object) rather than msg (a string).
I've updated your code snippet to do this:
var app = angular.module('app', []);
app.controller('Ctrl', function Ctrl($scope) {
$scope.test = {msg : 'initial message'};
})
app.directive('eDir', function eDir($timeout) {
return {
restrict: 'E',
scope: {
attr: '='
},
template: '<div>$scope.attr: {{attr.msg}}</div>'+
'<div>eDirCtrl.attr: {{eDirCtrl.attr.msg}}</div>',
controller: function EDirCtrl($scope) {
var eDirCtrl = this;
eDirCtrl.attr = $scope.attr;
$timeout(function() {
$scope.attr.msg = 'changing $scope.attr also changes msg';
}, 2000);
},
controllerAs: 'eDirCtrl'
};
});
app.directive('aDir', function aDir($timeout) {
return {
restrict: 'A',
require: 'eDir',
link: linkFn
};
function linkFn(scope, element, attrs, eDirCtrl) {
$timeout(function() {
eDirCtrl.attr.msg = 'changing eDirCtrl.attr does not effect $scope.attr or msg';
}, 4000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl">
msg: <input type="text" ng-model="test.msg"><br>
<e-dir a-dir attr="test"></e-dir>
</div>
I have an object which consists of multiple arrays:
$scope.myArrays = {
array1: ['Pizza', 'Spaghetti'],
array2: ['Lasagne', 'Schnitzel']
};
Moreover, I have a custom directive to which I want to pass this object myArrays and bind those arrays to scope variables:
<my-directive my-data="myArrays"></my-directive>
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
arrayOne: '=myData.array1',
arrayTwo: '=myData.array2'
},
link: function(scope, elem) {
// get access to scope.array1 and scope.array2
}
};
});
All together in a fiddle for you to play around!
Is there a way to bind the arrays directly or do I need to bind arrays: '=myArrays' and access them like arrays.array1?
Binding has to be one to one, you cannot do that. Yes, you will have to access the arrays inside your directive.
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
},
link: function(scope, elem) {
scope.arrayOne = scope.myData.array1;
scope.arrayTwo = scope.myData.array2;
}
};
});
You can directly access scope.myData.array1 and scope.myDate.array2 inside the directive template if you dont have to process these arrays in the link function and get rid of it.
You could do this by just assigning them to scope fields:
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
},
link: function(scope, elem) {
scope.arrayOne = myData.array1;
scope.arrayTwo = myData.array2;
}
};
});
However, I would recommeend to just bind the object and to get rid of the link-function. That way the directives code is a lot shorter, more readable, less "black magic" happens and the references inside the directive are more expressive:
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
myData: '='
}
};
});
Then you can just reference it inside the directive with myData.array1. Replace the '=' with '=someName' to reference it with someName.array1
your HTML should be :
<my-directive arrayone="myData.array1" arraytwo="myData.array2"></my-directive>
and your directive :
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
arrayOne: '=arrayone',
arrayTwo: '=arraytwo'
},
link:function(scope){
console.log('arrayOne :',scope.arrayOne);
console.log('arrayTwo :',scope.arrayTwo);
},
controller: function($scope) {
console.log('arrayOne :',$scope.arrayOne);
console.log('arrayTwo :',$scope.arrayTwo);
}
};
});
Demo
HTML-Partial:
<div ng-controller="MyCtrl">
<my-directive my-data="myArrays" array-one="myArrays.array1" array-two="myArrays.array2">
</my-directive>
</div>
Script:
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
arrayOne: '=',
arrayTwo: '='
},
link: function(scope, elem) {
// get access to scope.array1 and scope.array2
//console.log(scope.array1)
console.log(scope.arrayOne);
console.log(scope.arrayTwo);
}
};
})
.controller('MyCtrl', function($scope) {
$scope.myArrays = {
array1: ['Pizza', 'Spaghetti'],
array2: ['Lasagne', 'Schnitzel']
};
});
I have created two directives and inserted the first directive into the second one. The content of template attribute works fine but the scope variable of the controller is not recognized. Please provide me solution on this
sample link: http://jsbin.com/zugeginihe/2/
You didn't provide the attribute for the second directive.
HTML
<div second-dir first-dir-scope="content">
<div first-dir first-dir-scope="content"></div>
</div>
Link demo: http://jsbin.com/jotagiwolu/2/edit
The best option would using parent directive, We could take use of require option of directive like require: '?secondDir' in firstDir
Code
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope) {
$scope.content = "test1";
});
myApp.directive("firstDir", function() {
return {
restrict: "AE",
require: '?secondDir',
scope: {
firstDirScope: "="
},
template: "<div>first content</div>",
link: function(scope, element, attrs, secondDir) {
console.log(scope.firstDirScope, 'first');
}
};
});
myApp.directive("secondDir", function() {
return {
restrict: "AE",
scope: {
firstDirScope: "="
},
controller: function($scope) {
console.log($scope.firstDirScope, 'second');
}
};
});
Working JSBin
I want to create two directives that have the following structure:
<div ng-app="myApp">
<div ui-foo="test">
<div ui-bar="test2"></div>
</div>
</div>
First directive is uiFoo, the second one is uiBar.
To define these directives I have setup the following module definition:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
}
};
}
).directive('uiBar',
function() {
return {
restrict: 'A',
require: '^uiFoo',
scope: true,
link: function($scope, element, attrs, uiBarController) {
uiBarController.message();
}
};
}
);
angular.module('myApp', ['ui']);
The problem that I am experiencing is known as error/$compile/ctreq (Controller 'uiFoo', required by directive 'uiBar', can't be found!) and the documentation for it can be found here (https://docs.angularjs.org/error/$compile/ctreq?p0=uiFoo&p1=uiBar). I know, a little lackluster.
It doesn't seem to solve my issue.
I've created a JSFiddle for this which you can find here http://jsfiddle.net/A8Vgk/1187/
Thanks!
Like the error says, you're missing the controller on the uiFoo directive.
When you use the require: ^uiFoo, it tells Angular that you want to have access to the controller in the directive called uiFoo.
You didn't define a controller in that directive, so you get the error.
Just define the controller:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
},
controller: function($scope) {
this.message = function () {
alert("works!");
}
}
};
}
)
Working Fiddle.