AngularJS : How to bind data to a Directive? - javascript

I have a problem with this:
app.directive('myDirective', function(){
return{
retrict: 'EA',
replace: false,
scope:{
fstData: '#',
sndData: '#'
},
template: '<div ng-controller="myController" arg="{{fstData}}"><h3>{{sndData}}</h3><li ng-repeat="event in eventsCat"></li></div>'
}
});
When I create a my-directive tag in the HTML, it doesn't bind fstData but if I delete {{fstData}}, and I put something, it works.
I think that I can't binding in a tag that contains a ng-controller attribute, but I need this attribute (args) because in myController I use it.
Thanks!
In myController I have this:
app.controller('myController', function($scope, $attrs){
var myVar = myArray[$attrs.arg];

Have you tried this approach?
app.directive('myDirective', function(){
return{
retrict: 'EA',
replace: false,
scope:{
fstData: '#',
sndData: '#'
},
link: function(scope ,element , attrs)
{
var markup = '<div ng-controller="myController" arg="'+scope.fstData+'"><h3>'+scope.sndData+'</h3><li ng-repeat="event in eventsCat"></li></div>' ;
element.append(markup);
}
}
});

Related

AngularJS Directive two way binding in isolated scope not reflecting in parent scope

I am trying to pass a scope array element to a directive and changing the value of that element inside the directive but when I print the values of the scope element the changes that made inside the directive is not affected in the parent scope. I created Isolated scope and provided two way binding using '=' in scope but It is not giving any change in the parent scope.
Attaching the code
Index.html
<div ng-app="dr" ng-controller="testCtrl">
<test word="word" ng-repeat="word in chat.words"></test>
<button ng-click="find();">
click
</button>
</div>
Javascript Part
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.chat= {words: [
'first', 'second', 'third'
]};
$scope.find = function(){
alert(JSON.stringify($scope.chat, null, 4));
}
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
template: "<input type='text' ng-model='word' />",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
Most of my search returned that putting '=' in directive scope will solve the issue, But no luck with that. can anyone point what is the issue, and how can I reflect the value in parent scope.
You pass a string to your directive, and this string isn't referenced because its not related to your array anymore
i guess you have to change your array properly
Something like the following should work:
var app = angular.module('dr', []);
app.controller("testCtrl", function($scope) {
$scope.word = 'test';
$scope.chat= {words: [
{'name':'first'}, {'name': 'second'}, {'name' : 'third'}
]};
$scope.find = function(){
alert(JSON.stringify($scope.chat, null, 4));
}
});
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
word: '='
},
template: "<input type='text' ng-model='word.name' />",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
<div ng-app="dr" ng-controller="testCtrl">
<pre>{{chat.words}}</pre>
<test word="word" ng-repeat="word in chat.words"></test>
<button ng-click="find();">
click
</button>
</div>
The directive can be made more efficient by using one-way (<) binding:
app.directive('test', function() {
return {
restrict: 'EA',
scope: {
̶w̶o̶r̶d̶:̶ ̶'̶=̶'̶
word: '<'
},
template: "<input type='text' ng-model='word.name' />",
replace: true,
link: function(scope, elm, attrs) {
}
}
});
One-way (<) binding has the additional advantage that it works with the $onChanges life-cyle hook.

How to pass transclusion down through nested directives in Angular?

I am trying to figure out how to pass a transclusion down through nested directives and bind to data in the inner-most directive. Think of it like a list type control where you bind it to a list of data and the transclusion is the template you want to use to display the data. Here's a basic example bound to just a single value (here's a plunk for it).
html
<body ng-app="myApp" ng-controller="AppCtrl as app">
<outer model="app.data"><div>{{ source.name }}</div></outer>
</body>
javascript
angular.module('myApp', [])
.controller('AppCtrl', [function() {
var ctrl = this;
ctrl.data = { name: "Han Solo" };
ctrl.welcomeMessage = 'Welcome to Angular';
}])
.directive('outer', function(){
return {
restrict: 'E',
transclude: true,
scope: {
model: '='
},
template: '<div class="outer"><inner my-data="model"><div ng-transclude></div></div></div>'
};
})
.directive('inner', function(){
return {
restrict: 'E',
transclude: true,
scope: {
source: '=myData'
},
template :'<div class="inner" my-transclude></div>'
};
})
.directive('myTransclude', function() {
return {
restrict: 'A',
transclude: 'element',
link: function(scope, element, attrs, controller, transclude) {
transclude(scope, function(clone) {
element.after(clone);
})
}
}
});
As you can see, the transcluded bit doesn't appear. Any thoughts?
In this case you don't have to use a custom transclude directive or any trick. The problem I found with your code is that transclude is being compiled to the parent scope by default. So, you can fix that by implementing the compile phase of your directive (this happens before the link phase). The implementation would look like the code below:
app.directive('inner', function () {
return {
restrict: 'E',
transclude: true,
scope: {
source: '=myData'
},
template: '<div class="inner" ng-transclude></div>',
compile: function (tElem, tAttrs, transclude) {
return function (scope, elem, attrs) { // link
transclude(scope, function (clone) {
elem.children('.inner').append(clone);
});
};
}
};
});
By doing this, you are forcing your directive to transclude for its isolated scope.
Thanks to Zach's answer, I found a different way to solve my issue. I've now put the template in a separate file and passed it's url down through the scopes and then inserting it with ng-include. Here's a Plunk of the solution.
html:
<body ng-app="myApp" ng-controller="AppCtrl as app">
<outer model="app.data" row-template-url="template.html"></outer>
</body>
template:
<div>{{ source.name }}</div>
javascript:
angular.module('myApp', [])
.controller('AppCtrl', [function() {
var ctrl = this;
ctrl.data = { name: "Han Solo" };
}])
.directive('outer', function(){
return {
restrict: 'E',
scope: {
model: '=',
rowTemplateUrl: '#'
},
template: '<div class="outer"><inner my-data="model" row-template-url="{{ rowTemplateUrl }}"></inner></div>'
};
})
.directive('inner', function(){
return {
restrict: 'E',
scope: {
source: '=myData',
rowTemplateUrl: '#'
},
template :'<div class="inner" ng-include="rowTemplateUrl"></div>'
};
});
You can pass your transclude all the way down to the third directive, but the problem I see is with the scope override. You want the {{ source.name }} to come from the inner directive, but by the time it compiles this in the first directive:
template: '<div class="outer"><inner my-data="model"><div ng-transclude></div></div></div>'
the {{ source.name }} has already been compiled using the outer's scope. The only way I can see this working the way you want is to manually do it with $compile... but maybe someone smarter than me can think of another way.
Demo Plunker

Interaction of directive and controller in AngularJS

I want to create a component that displays itself as a collapsible box.
When it is expanded, it should show the transcluded content; when it is collapsed it should only show its label.
myApp.directive('collapsingBox', function() {
return {
restrict: 'E',
transclude: true,
require: '^ngModel',
scope: {
ngModel: '='
},
template: '<div ng-controller="CollapseController" class="collapsingBox"><div class="label">Title: {{ ngModel.title }}</div><br/><div ng-transclude ng-show="expanded">Test</div></div>',
link: function($scope, element, attr) {
element.bind('click', function() {
alert('Clicked!');
$scope.toggle();
});
}
};
});
This component should be reusable and nestable, so I wanted to manage the values (like "title" and "expanded") in a controller that gets instantiated for every use of the directive:
myApp.controller('CollapseController', ['$scope', function($scope) {
$scope.expanded = true;
$scope.toggle = function() {
$scope.expanded = !$scope.expanded;
};
}]);
This "almost" seems to work:
http://plnkr.co/edit/pyYV0MAikXThvMO8BF69
The only thing that does not work seems to be accessing the controller's scope from the event handler bound during linking.
link: function($scope, element, attr) {
element.bind('click', function() {
alert('Clicked!');
$scope.toggle(); // this is an error -- toggle is not found in scope
});
}
Is this the correct (usual?) way to create one instance of the controller per use of the directive?
How can I access the toggle-Function from the handler?
Rather than using ng-controller on your directive's template, you need to put the controller in your directive's controller property:
return {
restrict: 'E',
transclude: true,
require: '^ngModel',
scope: {
ngModel: '='
},
template: '<div class="collapsingBox"><div class="label">Title: {{ ngModel.title }}</div><br/><div ng-transclude ng-show="expanded">Test</div></div>',
controller: 'CollapseController',
link: function($scope, element, attr) {
element.bind('click', function() {
alert('Clicked!');
$scope.toggle();
});
}
};
As it is CollapseController's scope will be a child scope of your directive's scope, which is why toggle() isn't showing up there.

Change href can't update the data which bind to ng-src or ng-href

Html
<div class="result" ng-controller="test">
<div>{{result}}</div>
<a ng-href="{{result}}"></a>
</div>
JS
App.controller('AppCtrl', function AppCtrl($scope){
$scope.result = "www.google.com";
}
In a jquery file I can't modify because of some reason, some code changed the value of href, like:
$('.result>a').attr('href','www.youtube.com');
I want the value of $scope.result in the controller also changed from "www.google.com" to "www.youtube.com". But the result value in the div didn't change after the jquery code. Do I need write directive to watch the href attribute by myself? Or there are some other way to use ng-href? I try to write the directive by myself, but it didn't work. I hope you can give me a small example. Thanks :)
Update:
This is my directive, it didn't work, after something like $('.result>a').attr('href','www.youtube.com'), the console didn't print "change!" and the $scope.result didn't change:
APP.directive('result', function() {
return {
restrict: 'E',
scope: {
ngModel: '='
},
template: "<div class='result'><a ng-href='{{ngModel}}' href=''></a></div>",
replace: true,
require: 'ngModel',
link: function(scope, element, attrs) {
var $element = $(element.children()[0]);
scope.$watch($element.attr('href'), function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});
Update Again: Still can't work...
Html:
<div class="result">
<a ng-href="{{result}}" ng-model="result" class="resulta"></a>
</div>
JS:
APP.directive('resulta', function() {
return {
restrict: 'C',
scope: {
ngModel: '='
},
link: function(scope, element, attrs) {
scope.$watch(attrs.href, function(newValue) {
console.log("change!");
scope.ngModel = newValue;
})
}
};
});
You can indeed create a custom directive to do it. See the example. I use transclude scope so you can put whatever you like in the link. I set 'replace: true' so the directive is removed and replaced with the <a>.
UPDATE
Using MutationObserver to watch for changes to the <a href>
var app = angular.module("MyApp", []);
app.directive("myHref", function() {
return {
restrict: 'E',
replace: true,
transclude: true,
link: function(scope, elem, attrs) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
scope.$parent.result = mutation.target.href;
scope.$apply();
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(elem[0], config);
},
scope: {
myHref: '='
},
template: '<a target="_blank" ng-transclude href="{{myHref}}"></a>'
};
});
app.controller('AppCtrl', function($scope) {
$scope.result = "http://www.yahoo.com";
$scope.$watch('result', function() {
alert($scope.result);
});
});
setTimeout(function() {
$('.result > a ').attr('href', 'http://www.youtube.com');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="MyApp">
<div class="result" ng-controller="AppCtrl">
<my-href my-href="result">My Link</my-href>
</div>
</div>

Angular js directive using controller as syntax ng-click not working

I am having trouble getting a click event in a directive with an isolated scope to work using "controller as" syntax in Angular 1.3 the code for the directive is as follows:
myDirectives.directive('gsphotosquare', dirfxn);
function dirfxn() {
var directive = {
replace: false,
scope: {
photoInfo: '=',
photoBatchNum: '=',
thumbnailwidth: '='
},
restrict: 'EA',
controller: Ctrller,
controllerAs: 'ctrl',
template: '<div ng-click="ctrl.squareClicked()">test</div>',
//templateUrl: 'views/directives/gsphotosquare.html',
bindToController: true, // because the scope is isolated
link: linkFunc //adding this didn't help
};
return directive;
}
function Ctrller() {
var vm = this;
vm.squareClicked = function () {
alert('inside clickhandler for gsphotosquare directive');
};
}
function linkFunc(scope, el, attr, ctrl) {
el.bind('click', function () {
alert('inside clickhandler for gsphotosquare directive');
});
}
And here is how the directive is used in the DOM:
<span class="input-label">General Site Photos</span>
<div class=" item row">
<gsphotosquare photo-info="mt.photos.v1f1[0]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
<gsphotosquare photo-info="mt.photos.v1f1[1]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
<gsphotosquare photo-info="mt.photos.v1f1[2]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
<gsphotosquare photo-info="mt.photos.v1f1[3]" photo-batch-num="mt.photoBatchNum" ></gsphotosquare>
</div>
Any ideas why clicking on the rendered directive doesn't show the alert?
Try defining your controller a little differently:
myDirectives.controller('Ctrller', Ctrller);
then in your directive:
controller: 'Ctrller as ctrl',

Categories

Resources