Why ng-click not working on custom directive template? - angularjs

I want to create a drop down filter in my project. So, I created the drop down list using directive, in which the list contains ng-click event in the template. I don't know where I was wrong. Kindly, provide solution. Thanks in Advance.
My HTML file
<div ng-controller="drop">
<a ng-click="toggleList">Select</a>
<div ng-if="toggleDrop">
<drop-down></drop-down>
</div>
</div>
My Controller Code
angular.module('myApp', [])
.controller('drop', ['$scope', function($scope){
$scope.toggleDrop = false;
$scope.filterList = ['One','Two','Three'];
$scope.toggleList = function() {
$scope.toggleDrop = !$scope.toggleDrop;
}
$scope.filterContent = function() {
alert('dfdf')
}
}]);
My Directive Code
angular.module('myApp', [])
.directive('dropDown', function() {
return {
restrict: 'E',
templateUrl: 'drop.html'
controller: drop
}
});
My Directive Template File
<ul>
<li ng-repeat="items in filterList" ng-click="filterContent()">{{items}}</li>
</ul>
Everything works fine except the ng-click behaviour. Thanks in Advance.

There are few issues with your code,
(i) Your directive should not have a new module with empty dependencies, change it as,
angular.module('myApp')
.directive('dropDown', function()
(ii) You are missing a comma after the controller inside directive,
angular.module('myApp')
.directive('dropDown', function() {
return {
restrict: 'E',
templateUrl: 'drop.html',
controller: 'drop'
}
});
(iii)Should be toggleList() which is a function,
<a ng-click="toggleList()">Select</a>
DEMO

You're missing parenthesis to call function on ng-click
ng-click="toggleList()"
Also in directive code don't declare angular module once again. If you that it will wipe out old registered component from that module. Use angular.module('moduleName')(that will return create module) while registering new component to module
angular.module('myApp', [])
should be
//module getter
angular.module('myApp')
Additionally directive has wrong DDO, correct it to below
return {
restrict: 'E',
templateUrl: 'drop.html', //added `,` here
//I don't think so you need controller here as you shared the parent controller
//wrap with `'` but it will create `drop` controller instance inside directive again
//controller: 'drop'
}

You have given the function name 'toggleList' but you have not called the function. It should work when you call the function as follows:
<a ng-click="toggleList()">Select</a>
You are missing parenthesis in the function.
Thanks

Related

Access isolated scope in angular directive template

I am currently writing an angular directive that uses a template in a different HTML file and an isolated template. The directive gets some string via # to its scope and that value is available in teh controller function.
Somehow its not available via {{}} in the HTML template. Why is that so? How can I change that? I read something about the template using the parent scope but I don't fully understand that.
Here is a code example:
angular.module('moduleName')
.directive('aGreatDirective', function () {
return {
restrict: 'E',
scope: {
mapid: '#'
},
templateUrl: "path/to/template.html",
controller: ['$scope', function (scope) {
console.log($scope.mapid); // is defined
}
}
});
And the html code for the template:
<div id="{{mapid}}"></div>
The result in the browser is exactly the same where it should be:
<div id="theValueOfmapid"></div>
Thanks for your help!
PS Here is a jsfiddle: fiddle
Your fiddle was incorrect since you didn't have your controller defined or $scope injected properly. The following will work just fine:
template:
<div ng-controller="MyCtrl">
<a-great-directive mapid="thisisthemapid"></a-great-directive>
Some other code
</div>
js:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function () {
});
myApp.directive('aGreatDirective', function() {
return {
restrict: 'E',
scope: {
mapid: '#'
},
template: "<div id='{{mapid}}'> {{mapid}} </div>",
controller: ['$scope', function($scope) {
console.log($scope.mapid); // is defined
}
]}
});
Fiddle
Note that in my example, the injected variable in your directive's controller should be $scope, not scope, for consistency reasons.

AngularJS Controller - Directive -> invokation of Controller function from directive

I have a question concerning the visibility of function beween controllers and directives. I have a controller and a directive. The directive looks like this way
(function() {
'use strict';
angular
.module('myproject.schedule')
.directive('dirname', dirname);
function dirname() {
var directive = {
restrict: 'A',
replace: true,
scope: {
currentDateScheduler: "=",
...
},
controller: DirnameController,
controllerAs: 'vm',
bindToController: true,
templateUrl: ... directive.html
My controller looks like this:
(function() {
'use strict';
angular
.module('myproject.schedule')
.controller('MyController', MyController);
...
In the directive.html file I have a ng-click which invoked functions of my controller - and this works fine.
Actually now I am not sure why? I thought that a directive has its own namespace and the functions of my controller is not visible in ... directive.html.
Thanks a lot your help!
Controller scope is available to any directive that appears as a child within the DOM element on which the controller is declared. E.g.
<div ng-controller="ctrl1">
<dirname></dirnam> <!-- this has access to ctrl1 scope -->
</div>
So if you were to use the directive within another controller it would have access to that controllers scope. This means that if the function doesn't exist in the controller that the directive declared under then the ng-click will do nothing.
In the directive you can declare a controller, anything declared in this controller will override the controller function of the same name within the directive. E.g.
angular.module('myApp',[])
.controller('myController',function($scope){
$scope.clickMe = function(){
alert('clicked from the controller');
}
})
.directive('dirname', function(){
return {
controller: function($scope){
$scope.clickMe = function(){ alert('clicked from directive'); };
},
};
});
controllers can also be nested. In this case the scope again has a top down effect, whereby a function defined in the top most controller is available to the dom elements enclosed in a child controller. Also if this child controller has the same function declared then these will override the functionality of the parent controller.
Hope this helps

AngularJS can't pass in different function when directive coupled with controller

I have a directive which I want to tightly couple with a controller as a component. I assumed I was following best practice by explicitly passing ion my functions even though I was declaring the controller to use. Here is an example:
app.js
var app = angular.module('plunker', [])
app
.controller('myCtrl', function($scope) {
$scope.output = '';
$scope.foo = function () {
$scope.output = 'foo';
}
$scope.bar = function () {
$scope.output = 'bar';
}
})
.directive('myDirective', function() {
return {
scope: {
output: '=',
foo: '&',
},
templateUrl: 'template.html',
replace: true,
controller: 'myCtrl',
};
})
template.html
<div>
<button ng-click="foo()">Click Foo</button>
<p>You clicked: <span style="color:red">{{output}}</span></p>
</div>
index.html
<body>
<my-directive
output="output"
foo="bar()"> <!-- pass in the *bar* function instead of the *foo* function -->
</my-directive>
</body>
Plunkr: http://plnkr.co/edit/Y4lhxuXbK9YbjAklR7v1?p=preview
Here, even though I'm passing in the bar() function, the output is 'foo' when the button is clicked. If I uncouple the controller by commenting out controller: 'myCtrl' in the directive, the output becomes 'bar'.
I thought I could declare the controller but still be free to pass in which functions I desire to the directive. It also seems that explicitly passing these functions in is a little redundant if the directive just looks up to the controller to find it (I can pass nothing into the directive and it still works).
This is especially problematic when testing as I would like to pass in my own stub functions to the directive, which at the moment I cannot do.
Is there some way to achieve what I want or am I doing something fundamentally wrong?
EDIT I meant to not have the controller declared in the HTML.
Remove the controller property on the directive:
.directive('myDirective', function() {
return {
scope: {
output: '=',
foo: '&',
},
templateUrl: 'template.html',
replace: true,
// controller: 'myCtrl',
};
})
You're wiring up the same controller to the directive as the parent, which is overwriting all the properties you're trying to pass in via isolate scope. The controller is wired up twice, once on the parent scope and then again on the directive. Removing this will allow you to pass in the function bar() and it will not be overwritten.
Here's the Plunker Demonstration
When running inside a directive, the $scope is initialized with output and foo variables before the controller constructor is called. Your controller is essentially overwriting these properties.
A simple check in your controller
if(!$scope.foo)
{
$scope.foo = function () {
$scope.output = 'foo';
}
}
Would work.
PS. I'm assuming your example is a simplification of your problem. If it's not, then the other answer's advice to simply remove the controller from the directive is the best approach.

Databinding to a controller inside a directive in angular

I'm new to angular and have the following directive:
angular.module('myApp')
.directive('myDirective', function () {
return {
templateUrl: '/views/partial-views/partial.html',
restrict: 'E',
controller : function(){
age : '5'
},
controllerAs : 'myCtrl'
};
});
I want to include the age on my page inside partial.html which looks like this:
<div ng-app="myApp" ng-controller="myCtrl as s">
{{s.age}}
</div>
However I am getting the following error:
Error: [ng:areq] Argument 'myCtrl' is not a function, got Object
Can anybody tell me what I'm doing wrong?
What Chandermani mentioned is absolutely correct. To be more precised, it can be written as,
Directive Definition
angular.module('myApp')
.directive('myDirective', function () {
return {
templateUrl: '/views/partial-views/partial.html',
restrict: 'E',
controller: ['$scope', function($scope){
$scope.age = '5'
}]
};
})
Usage
<div ng-app="myApp">
<my-directive>
{{age}}
</my-directive>
</div>
However, there's no meaning of defining a directive here. You can just use a controller definition to fulfill the same action.
There were two issues with you code. Firstly you don't to alias the controller again, by using ng-controller in your template so that needs to be removed.
Secondly the controller is a function not object, so use:
this.age = '5';

Isolated scope: value not updating

I am trying to expand on the bootstrap ui library with my own custom control. This control will be used in an AngularJS app. Currently, I'm getting stuck on the scoping.
My plunker is here
This plunker is a simplified version of a more complex control. The concept that I'm trying to highlight is the scoping. You will notice that the custom control, my-query, is pre-populated with the value of myController.$scope.query. You will also see that the query is put in the page underneath the custom control. As I type, the value does NOT get updated. Why? My code looks like the following:
myApp.directive('myQuery', [function() {
return {
restrict:'E',
transclude: true,
scope: {
query: '='
},
template: '<div ng-controller="myQueryController"><input type="text" ng-model="query" /><button ng-click="go_Click()">go</button></div>'
};
}]);
myApp.controller('myQueryController', ['$scope', function($scope) {
$scope.go_Click = function() {
$scope.$emit("goClicked");
};
}]);
What am I doing wrong?
In your directive template, you are adding an additional controller which is adding in another scope. That is what is causing the problem. Instead of doing it that way, move the controller logic into either a controller function or a link function defined on your directive, either will work.
Try this. Here's an example using a controller function. Note that I moved your original myQueryController inside the directive and removed the ng-controller directive from the myQuery directive's template.
'use strict';
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function($scope) {
$scope.queryValue = 'test';
$scope.$on('goClicked', function() {
$scope.performAction();
});
$scope.performAction = function() {
alert('Using ' + $scope.queryValue);
};
}]);
myApp.directive('myQuery', [function() {
return {
restrict:'E',
transclude: true,
scope: {
query: '='
},
template: '<div><input type="text" ng-model="query" /><button ng-click="go_Click()">go</button></div>',
controller : function ($scope) {
$scope.go_Click = function() {
$scope.$emit("goClicked");
};
}
};
}]);
<div ng-controller="myQueryController">
A controller creates a new scope. So <input type="text" ng-model="query" /> doesn't use query from the directive's scope but from the controller's scope. Instead of using a controller you can define the go_Clickfunction in the directive's link method.
Do you need this?:
http://plnkr.co/edit/6IrlnXvsi2Rneee0hGC8?p=preview
scope: {
model: '='
}
The problem was that you used a primitive type which was passed by value into your directive. Always use complex types which are passed by reference.

Resources