What is the preferred way to link/bind two directives together? I have a controller with two directives, first directive is a select element, after selecting option, second directive should process selected item value.
App code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
var sharedData = { selectedId: '' };
var vm = this;
vm.sharedData = sharedData;
});
app.directive('directiveA', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
selectedId: '='
},
template: '<select data-ng-model="vm.sharedData.selectedId" data-ng-options="currentSelect.Id as currentSelect.Name for currentSelect in vm.sharedData.availableSelects track by currentSelect.Id"><option value="">Select option</option></select><p>Directive A, selected ID: {{vm.sharedData.selectedId}}</p>',
bindToController: true,
controllerAs: 'vm',
controller: function() {
vm = this;
vm.sharedData = {
availableSelects: [
{Id:1, Name: 'Option 1'},
{Id:2, Name: 'Option 2'},
{Id:3, Name: 'Option 3'},
{Id:4, Name: 'Option 4'}
]
}
vm.logMessage = logMessage;
function logMessage(selectedId) {
console.log('directiveA: ' + selectedId);
}
},
link: function($scope, elem, attr, ctrl) {
attr.$observe('selectedId', function(selectedId) {
ctrl.logMessage(selectedId);
});
}
};
}]);
app.directive('directiveB', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
selectedId: '='
},
template: '<p>Directive B, selected ID: {{vm.sharedData.selectedId}}</p>',
bindToController: true,
controllerAs: 'vm',
controller: function() {
vm = this;
vm.logMessage = logMessage;
function logMessage(selectedId) {
console.log('directiveB: ' + selectedId);
}
},
link: function($scope, elem, attr, ctrl) {
attr.$observe('selectedId', function(selectedId) {
ctrl.logMessage(selectedId);
});
}
};
}]);
HTML code:
<!DOCTYPE html>
<html data-ng-app="plunker" data-ng-strict-di>
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link href="style.css" rel="stylesheet" />
<script data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js" data-require="angular.js#1.4.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
<p>MainCtrl, selected ID: {{vm.sharedData.selectedId}}</p>
<directive-a data-selected-id="vm.sharedData.selectedId"></directive-a>
<directive-b data-selected-id="vm.sharedData.selectedId"></directive-b>
</body>
</html>
Here is a Plunker example:
http://plnkr.co/edit/KVMGb8uAjUwD9eOsv72z?p=preview
What I'm doing wrong?
Best Regards,
The key issue revolves around your use of isolated scopes:
scope: {
selectedId: '='
},
With controllerAs binding:
controllerAs: 'vm',
What this essentially does, to put it basically, is it places the view model onto the directives scope, accessed through the alias you assign in the controllerAs. So basically in your html when you go:
<directive-a data-selected-id="vm.sharedData.selectedId"></directive-a>
You are actually accessing the directive-a view model, NOT the MainCtrl view model. BECAUSE you set directive-a as having an isolate scope... which is a new scope, isolated from the MainCtrl.
What you need to do is more along the following lines:
http://plnkr.co/edit/wU709MPdqn5m2fF8gX23?p=preview
EDIT
TLDR: I would recommend having unique view model aliases (controllerAs) when working with isolated scopes to properly reflect the fact that they are not the same view model.
Related
i am familiar with the syntax of controller & name but i'm trying to create a generic directive that will get a list of items and for each item i need to specify a controller.
This is my main directive:
function controlPanel() {
var directive = {
restrict: 'E',
replace: true,
scope: {
controlPanelItems: "=sbControlPanelItems"
},
templateUrl: 'control-panel.html',
link: link
};
return directive;
function link(scope, element) {
}
}
Here is the directive template:
<sb-control-panel-item ng-repeat="controlPanelItem in controlPanelItems"
sb-title="controlPanelItem.title"
sb-template-url="controlPanelItem.templateUrl"
sb-control-panel-item-controller="controlPanelItem.controller"></sb-control-panel-item>
My issue is with the sb-control-panel-item-controller attribute.
Angular throws exception when i'm passing variable, it work's great when i'm passing simple string (the name of the controller).
Here is the code of the control-panel-item directive:
function controlPanelItem() {
var directive = {
restrict: 'E',
replace: true,
scope: {
title: '=sbTitle',
templateUrl: '=sbTemplateUrl'
},
templateUrl: 'control_panel_item.html',
controller: '#',
name: 'sbControlPanelItemController',
link: link
};
return directive;
function link(scope, iElement, iAttributes, controller) {
}
}
Maybe there is a way to inject the controller through the link function and then i'll just pass it through the scope?
You can use the $controller service to instantiate whatever controller dynamically inside the directive, check this plunkr.
Just bear in mind that if you wanted to specify a controller statically now, you would need to enclose it in single quotes.
Basically the code would be like:
function MainCtrl() {
this.firstCtrl = 'FirstCtrl';
this.secondCtrl = 'SecondCtrl';
}
function FirstCtrl() {
this.name = 'First Controller';
}
function SecondCtrl() {
this.name = 'Second Controller';
}
function fooDirective() {
return {
scope: {
ctrl: '='
},
template: '<div>{{foo.name}}</div>',
controller: ['$controller', '$scope', function($controller, $scope) {
var foo = $controller($scope.ctrl, {$scope: $scope});
return foo;
}],
controllerAs: 'foo',
link: function ($scope, $element, $attrs, $ctrl) {
console.log($scope.ctrl);
}
};
}
angular
.module('app', [])
.directive('fooDirective', fooDirective)
.controller('MainCtrl', MainCtrl)
.controller('FirstCtrl', FirstCtrl)
.controller('SecondCtrl', SecondCtrl);
and this would be the HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="MainCtrl as main">
<h1>
Test
</h1>
<foo-directive ctrl="main.firstCtrl">
"name: " {{foo.name}}
</foo-directive>
<foo-directive ctrl="main.secondCtrl">
{{foo.name}}
</foo-directive>
</body>
</html>
========================================================================
WRONG OLD ANSWER
From this blog entry seems to be an undocumented property that allows you to do exactly what you need.
function FirstCtrl() {
this.name = 'First Controller';
}
function SecondCtrl() {
this.name = 'Second Controller';
}
function fooDirective() {
return {
scope: {},
name: 'ctrl',
controller: '#',
controllerAs: 'foo',
template: '<div></div>',
link: function ($scope, $element, $attrs, $ctrl) {
}
};
}
angular
.module('app', [])
.directive('fooDirective', fooDirective)
.controller('FirstCtrl', FirstCtrl)
.controller('SecondCtrl', SecondCtrl);
So all you need to do in your directive is add a property name linked to the attribute you will use with the name of your controller.
<foo-directive ctrl="FirstCtrl"></foo-directive>
<foo-directive ctrl="SecondCtrl"></foo-directive>
If your directive, as per your question, needs to be from a property rather than a string, use {{}} notation:
<sb-control-panel-item ng-repeat="controlPanelItem in controlPanelItems"
sb-title="controlPanelItem.title"
sb-template-url="controlPanelItem.templateUrl"
sb-control-panel-item-controller="{{controlPanelItem.controller}}"></sb-control-panel-item>
I have a categoryList directive that generates a select box of categories. This directive works fine and when I select a category, the outer controller scoped property mentioned in ngModel is updated properly. But when I put categoryList in another directive (subCategoryList), the scope of subCategoryList isn't updated properly.
You can see this problematic behavior in this snippet: In the first select box, you can see that any change will be updated in the outer scope, but in the second select box, the changes are "stuck" inside the categoryList directive, and doesn't affect subCategoryList
angular.module('plunker', [])
.controller('MainCtrl', function($scope) {
}).directive('categoryList', function () {
return {
restrict: 'E',
template: 'categoryList debug: {{model}}<br/><br/><select ng-options="cat as cat.name for cat in categories track by cat.id" ng-model="model" class="form-control"><option value="">{{emptyOptLabel}}</option></select>',
scope: {
model: '=ngModel',
categories: '=?',
catIdField: '#',
emptyOptLabel:'#'
},
link: categoryListLink
};
function categoryListLink(scope, el, attrs) {
if (angular.isUndefined(scope.catIdField)) {
scope.catIdField = 'categoryId';
}
if(angular.isUndefined(scope.emptyOptLabel)){
scope.emptyOptLabel = 'category';
}
if( !scope.categories ) {
scope.categories = [
{
'categoryId':123,
'name':'cat1',
'subCategories':[
{
'subCategoryId':123,
'name':'subcat1'
}
]
}
];
}
prepareCats(scope.categories);
function prepareCats(cats){
cats.forEach(function (cat) {
cat.id = cat[scope.catIdField];
});
return cats;
}
}
}).directive('subCategoryList', function () {
return {
restrict: 'E',
template: 'subCategoryList debug:{{model}}<br/><br/><category-list ng-if="parent && parent.subCategories.length !== 0" ng-model="model" categories="parent.subCategories" cat-id-field="subCategoryId" empty-opt-label="sub category"></category-list>',
scope: {
model: '=ngModel',
parent: '='
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script data-require="angular.js#1.*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
Outer debug: {{main.cat}}<br/><br/>
<category-list ng-model="main.cat" empty-opt-label="category"></category-list><br/><br/>
<sub-category-list ng-model="main.subcat" parent="main.cat"></sub-category-list>
</body>
</html>
Someone has an idea what could be the problem here?
This is a scope issue related with ng-if in directive subCategoryList. If you remove it, the code starts working.
I'm working on a page that is made up of 5 directives, for example:
<directive-one></directive-one>
<directive-two></directive-two>
<directive-three></directive-three>
<directive-four></directive-four>
<directive-five></directive-five>
I would like to be able to re-order these on demand so that a user can control how their page looks. The only way I could think of doing that was putting them in an ng-repeat:
$scope.directiveOrder = [{
name: "directive-one",
html: $sce.trustAsHtml('<directive-one></directive-one>'),
order: 1
}, ...
HTML:
<div ng-repeat="directive in directiveOrder" ng-bind-html="directive.html">
{{directive.html}}
</div>
This will give me the right tags, but they aren't processed as directives by angular. Is there a way around that? I'm assuming it's something to do with $sce not handling it, but I might be way off?
Try creating a new directive and using $compile to render each directive:
https://jsfiddle.net/HB7LU/18670/
http://odetocode.com/blogs/scott/archive/2014/05/07/using-compile-in-angular.aspx
HTML
<div ng-controller="MyCtrl">
<button ng-click="reOrder()">Re-Order</button>
<div ng-repeat="d in directives">
<render template="d.name"></render>
</div>
</div>
JS
var myApp = angular.module('myApp',[])
.directive('directiveOne', function() {
return {
restrict: 'E',
scope: {},
template: '<h1>{{obj.title}}</h1>',
controller: function ($scope) {
$scope.obj = {title: 'Directive One'};
}
}
})
.directive('directiveTwo', function() {
return {
restrict: 'E',
scope: {},
template: '<h1>{{obj.title}}</h1>',
controller: function ($scope) {
$scope.obj = {title: 'Directive Two'};
}
}
})
.directive("render", function($compile){
return {
restrict: 'E',
scope: {
template: '='
},
link: function(scope, element){
var template = '<' + scope.template + '></' + scope.template + '>';
element.append($compile(template)(scope));
}
}
})
.controller('MyCtrl', function($scope, $compile) {
$scope.directives = [{
name: 'directive-one'
}, {
name: 'directive-two'
}];
$scope.reOrder = function () {
$scope.directives.push($scope.directives.shift());
console.log($scope.directives);
};
});
I hope You can easily done it.
var myApp = angular.module('myApp',[])
.directive('directiveOne', function() {
return {
restrict: 'E',
scope: {},
template: '<h1>{{obj.title}}</h1>',
controller: function ($scope) {
$scope.obj = {title: 'Directive One'};
}
}
})
.directive('directiveTwo', function() {
return {
restrict: 'E',
scope: {},
template: '<h1>{{obj.title}}</h1>',
controller: function ($scope) {
$scope.obj = {title: 'Directive Two'};
}
}
});
myApp.controller('ctrl',function($scope){
$scope.data = [{name:'directive-one'},{name:'directive-two'}];
});
<html ng-app='myApp'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js"></script>
</head>
<body ng-controller='ctrl'>
<div ng-repeat='item in data'>
<item.name></item.name>
<directive-one></directive-one>
</body>
</html>
I have trouble getting my transcluding directive to work. I want to do the following: Create a directive that outputs a list where the content of each item is defined by transcluded content. E.g:
<op-list items="myItems">
<span class="item">{{item.title}}</span>
</op-list>
so I would use ng-repeat inside op-list's template and must be able to access the scope created by ng-repeat inside the transcluded content.
This is what I've done so far:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function ($scope) {
$scope.myModel = {
name: 'Superhero',
items: [{
title: 'item 1'
}, {
title: 'item 2'
}]
};
}]);
myApp.directive('opList', function () {
return {
template: '<div>' +
'<div>items ({{items.length}}):</div>' +
'<div ng-transclude ng-repeat="item in items"></div>' +
'</div>',
restrict: 'E',
replace: true,
transclude: true,
scope: {
items: '='
}
};
});
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
<div>Hello, {{myModel.name}}!</div>
<op-list items="myModel.items">
<span>title: {{item.title}}|{{$scope}}|{{scope}}|{{items}}</span>
</op-list>
</div>
</html>
Check if this works:
myApp.directive('opList', ['$scope', function ($scope) {
return {
template: '<div>' +
'<div>items ({{model.items.length}}):</div>' +
'<ng-transclude ng-repeat="item in model.items"></ng-transclude>' +
'</div>',
restrict: 'E',
replace: true,
transclude: true,
scope: {
items: '='
}
};
}]);
If it doesn't then try to inspect $scope in console and see if you're able to access your model.
I have two nested directives for building a treeview in Angular:
Parent directive:
myApp.directive('nodes', function() {
return {
restrict: "E",
replace: true,
scope: {
nodes: '='
},
template: "<ul><node ng-repeat='node in nodes' node='node'></node></ul>"
}
});
Child directive:
myApp.directive('node', function($compile) {
return {
restrict: "E",
replace: true,
scope: {
node: '='
},
template: "<li>{{node.ObjectName}}</li>",
link: function(scope, element, attrs) {
if (angular.isArray(scope.node.Children)) {
element.append("<nodes nodes='node.Children'></nodes>");
$compile('<nodes nodes="node.Children"></nodes>')(scope, function(cloned, scope) {
element.append(cloned);
});
}
}
}
});
The controller:
function myController($scope, DataService) {
$scope.init = function() {
DataService.getData(0, 0).then(function(data) {
$scope.treeNodes = $.parseJSON(data.d);
});
}
$scope.focusNode = function(prmNode) {
console.log(prmNode);
}
}
HTML:
<div ng-app="testTree" ng-controller="myController">
<div ng-init="init()">
<nodes nodes='treeNodes'></nodes>
</div>
</div>
My question is how can I implement a click on the <li> which will call the "focusNode" function in the controller?
You could pass in the function through an attribute.
Javascript
var myApp = angular.module('myApp', []);
myApp.directive('nodes', function() {
return {
restrict: "E",
replace: true,
scope: {
nodes: '=',
clickFn: '&'
},
template: "<ul><node ng-repeat='node in nodes' node='node' click-fn='clickFn()'></node></ul>"
}
});
myApp.directive('node', function($compile) {
return {
restrict: "E",
replace: true,
scope: {
node: '=',
clickFn: '&'
},
template: "<li><span ng-click='clickFn()(node)'>{{node.ObjectName}}</span></li>",
link: function(scope, element, attrs) {
if (angular.isArray(scope.node.Children)) {
element.append("<nodes nodes='node.Children' click-fn='clickFn()'></nodes>");
$compile('<nodes nodes="node.Children" click-fn="clickFn()"></nodes>')(scope, function(cloned, scope) {
element.append(cloned);
});
}
}
}
});
function myController($scope) {
$scope.focusNode = function(prmNode) {
console.log(prmNode);
}
$scope.root = {
ObjectName: 'Root',
Children:[{
ObjectName: 'A',
Children: [{
ObjectName: 'B'
}, {
ObjectName: 'C'
}]
}]
};
}
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#*" data-semver="1.2.8" src="http://code.angularjs.org/1.2.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='myApp' ng-controller="myController">
<node node="root" click-fn="focusNode"></node>
</body>
</html>
Since I can't comment until I get 50 rep cred :(...
I just wanted to add that I also got an error when trying the plunkr that W.L.Jared shared above. To fix the error, I changed the controller from a global function to:
angular.module('myApp').controller('myController', function($scope){...})
The error went away.
Good answer though :) Exactly what I was looking for.