I have a simple function in my controller that, when called in my template, works perfectly, as below:
In my controller:
$scope.save = function(arg){ ... }
In my template:
<input ng-model="namespace" ng-change="save(namespace)">
So I created a directive, and this function was not propagated anymore:
In my directive:
.directive('genericField', function() {
return {
scope: {
namespace: '=',
ngChange: '&',
save: '&',
},
template: '<input ng-model="namespace" ng-change="save(namespace)">',
}
})
And in my template:
<generic-field namespace="name"></generic-field>
What am I missing here? Any light on this problem?
Thank you
Change your codes as below.
Directive :
.directive('genericField', function() {
return {
restrict: 'AE',
scope: {
save: '&'
},
template: '<input ng-model="namespace" ng-change="save({arg : namespace})">',
}
})
HTML:
<generic-field namespace="name" save="save(arg)"></generic-field>
Fiddle
Related
I need to pass function defined in directive to another one , my code is something like below
angular
.module('myApp')
.controller('myAppCtrl', function($scope) {})
.directive('first', function() {
return {
restrict: 'E',
scope: {
originFn: '&',
},
template: '<button ng-click="originFn()" >Click</button>',
controller: function() {
var self = this;
self.originFn = function() {
console.log('called from First');
};
},
};
})
.directive('second', function() {
return {
restrict: 'E',
scope: {
passedFn: '&',
},
template: '<button ng-click="passedFn()" >Click</button>',
};
});
html
<div ng-controller="myAppCtrl">
<first origin-fn="originFn" />
<second passed-fn="originFn" />
</div>;
when click on second button origin function not called ,
How can pass function to be called inside second directive ?
Both of directives are siblings, there is nothing in common, one directive can't call other directive controller without being it child.
So, if you can nest second directive into the first, you can use require functionality to get the parent directive controller.
.directive('second', function () {
return {
restrict: 'E',
require: '^^first',
scope: {},
template: '<button ng-click="innerFunc()" >Click</button>',
link: function ($scope, $elem, $attr, firstCtrl) {
// -------------------------------------^
$scope.innerFunc = firstCtrl.originFn;
}
};
})
<div ng-controller="myAppCtrl">
<first>
<second></second>
</first>
</div>
For more complete example.
export function triMenuItemDirective() {
var directive = {
restrict: 'E',
require: '^triMenu',
scope: {
item: '='
},
// replace: true,
template: require('./menu-item-dropdown.tmpl.html'),
controller: triMenuItemController,
controllerAs: 'triMenuItem',
bindToController: true
};
return directive;
}
I need to load different html depending on item.
With the old way you could do:
template: '<div ng-include="::triMenuItem.item.template"></div>',
And in Controller
triMenuItem.item.template = 'app/components/menu/menu-item-' + triMenuItem.item.type + '.tmpl.html';
How do I achive this with webpack?
Something like
template: require('./menu-item-{{triMenuItem.item.type}}.tmpl.html'),
I think that to do this, you have at least three different approaches:
1- Use $templateCache and then pass a string variable to ng-include
.directive('myDirective', ['$templateCache', function ($templateCache) {
return {
scope: {
item: '='
},
template: '<div ng-include="content"></div>',
link: function (scope) {
$templateCache.put('a.tpl.html', require('./a.html'));
$templateCache.put('b.tpl.html', require('./b.html'));
scope.content = (scope.item === 'a') ? 'a.tpl.html' : 'b.tpl.html';
}
}
}]);
2- Use ng-bind-html.
app.directive('myDirective', ['$sce', function ($sce) {
return {
scope: {
item: '='
},
template: '<div ng-bind-html="content"></div>',
link: function (scope) {
if(scope.item === 'a')
scope.content = $sce.trustAsHtml(require('./a.html'));
}
}
}]);
3- Use ng-if. Maybe the less dynamic solution of the three, but is pretty simple if your requirements let you do it.
app.directive('myDirective', function () {
return {
scope: {
bool: '='
},
template: `
<div>
<div ng-if="item === 'a'">${require('./a.html')}</div>
<div ng-if="item === 'b'">${require('./b.html')}</div>
</div>
`
}
});
So this is a simple example i just wrote up for the sake of this question, I'm curious if I'm able to use a directive and pass in an object to the directive's attribute, all in the template, not templateUrl. I would think it would work something like this:
angular.module('myModule')
.directive('someDirective', function() {
return {
scope: {
u: '=',
},
template: '<avatar user="u"></avatar>',
};
});
Yes you can! And it doesn't matter the definition order.
app.directive("directive1", function() {
return {
restrict: 'E',
scope: {
u: '#'
},
template : "<h4>{{u}}</h4><directive2 user='{{u}}'></directive2>"
};
});
app.directive("directive2", function() {
return {
restrict: 'E',
scope: {
user: '#'
},
template : "<h1>{{user}}</h1>"
};
});
See it in action in this jsfiddle
Yes, it's easy to pass your state through scope attributes. Here's a plunkr that demonstrates the concept.
app = angular.module('app',[])
.directive('someDirective', function() {
return {
scope: {
u: '=',
},
template: '<avatar user="u"></avatar>',
};
}).directive('avatar', function() {
return {
scope: {
user: '=',
},
template: '<span>{{user.name}}</span>',
};
})
I have the example below.
HTML:
<body ng-controller="MainCtrl as MgtCtrl">
<p>Hello {{MgtCtrl.name}}!</p>
<p>Result is {{MgtCtrl.result}}!</p>
<output-content data="MgtCtrl.name" result="MgtCtrl.result"></output-content>
</body>
JavaScript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var MgtCtrl = this;
MgtCtrl.name = 'World';
MgtCtrl.result = "no";
MgtCtrl.changeLabel = function() {
alert('changeLabel');
MgtCtrl.result = 'yes';
}
});
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
},
controller: 'MainCtrl',
controllerAs: 'MgtCtrl'
};
});
ouputContent.html:
<div>
{{data}}
<button ng-click="MgtCtrl.changeLabel()">Change</button>
</div>
Plunker is: http://plnkr.co/edit/BW8VDyCaRnRgxE8I9JJy
I would like the result to be 'yes' when I click on the 'Change' button.
It doesn't work because of the named controller.
Could you please explain to me how to write the directive to do so ?
Regards.
You never was binding the scope variables to the named controller in the directive.
You must add the attribute bindToController: true to the directive definition like this plunker:
http://plnkr.co/edit/2QdnkpeuTM6adG9KoyJT?p=preview
Directive code:
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
},
controller: 'MainCtrl',
controllerAs: 'MgtCtrl',
bindToController: true
};
});
This go to add the data and result binding to the respective directive controller.
I think in this case you don't need to specify controller in the directive.
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
}
};
});
Also html shoul be updated:
<body ng-controller="MainCtrl as MgtCtrl">
<p>Hello {{MgtCtrl.name}}!</p>
<p>Result is {{MgtCtrl.result}}!</p>
<output-content data="MgtCtrl.name" result="MgtCtrl.result" change-label="MgtCtrl.changeLabel()"></output-content>
</body>
DEMO
Here is a simplified version of the two directives I have, my-input and another-directive:
HTML:
<body ng-controller="AppCtrl">
<another-directive>
<my-input my-input-model="data.firstName"></my-input>
</another-directive>
</body>
JS:
.directive('myInput', function() {
return {
restrict: 'E',
replace: true,
scope: {
model: '=myInputModel'
},
template: '<input type="text" ng-model="model">'
};
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
scope: {},
compile: function(element) {
var html = element.html();
return function(scope) {
var output = angular.element(
'<div class="another-directive">' +
html +
'</div>'
);
$compile(output)(scope);
element.empty().append(output); // This line breaks the binding
};
}
};
});
As you can see in the demo, if I remove element.empty().append(output);, everything works fine, i.e. changes in the input field are reflected in controller's data. But, adding this line, breaks the binding.
Why is this happening?
PLAYGROUND HERE
The element.empty() call is destroying all child nodes of element. In this case, element is the html representation of another-directive. When you are calling .empty() on it, it is trying to destroy its child directive my-input and any scopes/data-bindings that go with it.
A somewhat unrelated note about your example. You should look into using transclusion to nest html within a directive, like you are doing with another-directive. You can find more info here: https://docs.angularjs.org/api/ng/service/$compile#transclusion
I think a little bit context as to what you are trying to do well be helpful. I am assuming you want to wrap the my-input directive in another-directive ( some sort of parent pane ). You could accomplish this using ng transclude. i.e
angular.module('App', []).controller('AppCtrl', function($scope) {
$scope.data = {
firstName: 'David'
};
$scope.test = "My test data";
}).directive('myInput', function() {
return {
restrict: 'E',
replace: true,
scope: {
model: '=myInputModel'
},
template: '<input type="text" ng-model="model">'
};
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
transclude: true,
scope: {},
template : '<div class="another-directive"><div ng-transclude></div></div>'
};
});
It works if you require ngModel
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
require:'ngModel',
scope: {},
...