This question already has answers here:
Why does Chrome debugger think closed local variable is undefined?
(7 answers)
Closed 5 years ago.
Consider the following controller
angular.module('app')
.controller('formCtrl', ['$scope', '$http', function($scope, $http) {
$scope.var = 1;
$scope.updateData = function () {
debugger; // <-- $scope is undefined here!
}
}]);
dirrective is as follows...
angular.module('app')
.directive('formL', function() {
return {
restrict: 'E',
scope: {
items: '=info'
},
controller: 'formCtrl',
templateUrl: 'js/form/form.html'
};
});
Template is the following
<form class="form-horizontal" ng-controller="formCtrl as controller">
<input type="button" value="BTN" class="btn btn-success" ng-click="updateData()">
</form>
That does not seem to be the common problem (at least I did not found something simmilar in Google and on SO), when I hit button and get into controller $scope is undefined. And at the same time this is equal to $scope as it should be.
What should I do to make $scope be visible inside updateData?
PS. angular version is 1.6.5
UPDATE. I've change directive name from form to formL into above template. form is definetelly not the best name for a dirrective, but it's not the name I have in project, it's a bad simplification of the name for this question. So the problem is not caused by the name of dirrective
The main problem is your directive element matching. It's an infinite loop because your directive template also includes the directive element form. So your directive getting binded again and again and again.
Please check this runnable DEMO FIDDLE and rename your directive element. Do not use form or modify your template and outsource the form element. You also do not need to define a ng-controller inside your form element, while your controller is defined by the directive near controller: 'formCtrl'.
View
<div>
<my-form></my-form>
</div>
AngularJS application
var myApp = angular.module('myApp',[]);
myApp.controller('formCtrl', function ($scope) {
$scope.btn = 'BTN';
$scope.updateData = function () {
$scope.btn = 'BTN clicked';
}
});
myApp.directive('myForm', function () {
return {
restrict: 'E',
replace: true,
template: '<form class="form-horizontal"><input type="button" ng-value="btn" class="btn btn-success" ng-click="updateData()"></form>',
controller: 'formCtrl'
}
});
Update due to question update:
$scope is available inside your $scope function updateData(). Please compare your solution which mine above.
`
Related
I have an edit form for updating answers in a forum:
<div ng-repeat="answer in question.answers">
...
<div ng-show="answer.editMode" class="card pam">
<edit-answer-form
answer="answer"
></edit-answer-form>
</div>
</div>
The edit answer form is as below:
{{answer.body}} <!--This appears on screen fine-->
<form ng-submit=editAnswer() method="POST">
<input type="text" ng-model="answer.body" />
<button type="submit">Edit</button>
</form>
The Javascript for the directive is:
app.directive('editAnswerForm', function() {
var editAnswerController = ['$scope', 'flashMessageService', 'answerService', '$log', function($scope, flashMessageService, answerService, $log) {
var logger = $log.getInstance('editAnswerFormDirective');
$scope.editAnswer = function() {
logger.info("Edited answer to send to service ", $scope.answer);
answerService.editAnswer($scope.answer).then(function success(response) {
flashMessageService.flashMessageSuccess("Your answer has been edited");
}, function error(response) {
flashMessageService.flashMessageError("Error editing answer");
logger.error("Error editing answer: ", response);
})
};
}];
return {
// restrict: 'E',
templateUrl: '/angular/app/answer/editAnswer.html',
controller: editAnswerController,
scope: {
answer: '='
}
}
});
The $scope.answer is being passed to the directive fine (the answer will appear on screen when putting {{answer.xxx}} on the screen). However in the form, the answer.body value is not present, nor does it update the model when writing into the input field, or logging out the values when submitting the form.
I have a similar directive/form for updating questions and that's working fine. The only difference is the answer is in a ng-repeat. Could it be something to do with this?
Any ideas why this is not working?
Thanks a lot.
I'm trying to implement a bound property for an angular component as explained in the component documentation and this example.
Unfortunately the values I'm assigning at the tag level or in the $onInit methods are never used. Nor is the value printed when I use it as a model value.
You can find the full code on plunker.
My binding definition:
(function(angular) {
'use strict';
function SearchResultController($scope, $element, $attrs) {
var ctrl = this;
ctrl.searchFor = 'nohting-ctor';
ctrl.$onInit = function() {
console.log('SearchResultController.$onInit: searchFor='+ctrl.searchFor);
ctrl.searchFor = 'nothing-int';
};
}
angular.module('myApp').component('searchResult', {
templateUrl: 'searchResult.html',
controller: SearchResultController,
bindings: {
searchFor: '<'
}
});
})(window.angular);
Template:
<p>SearchResult for <span ng-model="$ctrl.searchFor"</span></span></p>
How it's used:
<h1>Main Window</h1>
<search-input on-start-search="$ctrl.startSearch(value)"></search-input>
<search-result search-for="nothing-ext"></search-result>
None of the nothing-* values is evers shown.
Any ideas what's wrong?
The usage of you component is not correct. If you want to pass a string it should be quoted:
<search-result search-for="'nothing-ext'"></search-result>
Then next problem is that this line
<p>SearchResult for <span ng-model="$ctrl.searchFor"</span></span></p>
doesn't make sense, as ngModel directive is only valid for input controls. You want ngBind or simple {{ $ctrl.searchFor }}:
<p>SearchResult for <span ng-bind="$ctrl.searchFor"</span></span></p>
I want to use same directives multiple times in one controller in AngularJS. I want to create a list widget that can be used multiple times. I can display two widgets at the same time under the same controller. But, I am unable to bind teamA and teamB data to ng-repeat in my directive. In addition to that, the code fails during addTeamMember() because datasource is undefined. I was hoping that datasource will be updated with teamA and teamB respectively.
Here is the HTML code.
<div ng-controller="myCtrl"><div class="container">
<my-directive datasource="model.teamA"></my-directive>
<my-directive datasource="model.teamB"></my-directive>
</div></div>
Controller.js:
angular.module('app',[])
.controller('myCtrl', [ '$scope', function($scope){
$scope.teamA = {};
$scope.teamB = {};
} ] );
Directive.js:
angular.module('app', [] )
.directive('myDirective', function(){
return{
restrict: 'AE',
templateUrl: 'directive_html.html',
scope: {
datasource: "=TeamMembers"
},
transclude: true,
link: function(scope, elem, attrs){
scope.addTeamMember = function(){
scope.datasource.push({});
};
scope.removeTeamMember = function(item){
scope.datasource.splice(item, 1);
};
}
};
}) ;
directive_html.html:
<div><div class="container">
<div class="form-group" ng-repeat="member in TeamMembers">
<textarea ng-model="member.text" rows="2"></textarea>
Remove
<div>
<button type="button" ng-click="addTeamMember()">Add</button>
</div></div>
Could anyone please help me out here? I want to create custom Widgets that can be used multiple places either in same controllers or in different controllers.
Thanks
As #Neozaru pointed out in comments. You are expecting the directive attribute to be called team-members here:
<div ng-controller="myCtrl"><div class="container">
<my-directive team-members="model.teamA"></my-directive>
<my-directive team-members="model.teamB"></my-directive>
</div></div>
You do this when you define the isolated scope as:
scope: {
datasource: "=TeamMembers"
}
The above line is saying, "team-members is what the outside attribute will be named, but internally I'll refer to the referenced object as scope.datasource".
I'm trying to call a function passed from a controller's scope into a directive via the "&" operation from the directive's controller. That method, however, is claimed by Angular to be undefined. After reading my code over and over, scouring the internet, and then repeating that process, I've decided to turn to help here.
Here's the relevant part of my controller. It contains the method I pass to my directive.
angular.module('myApp.controllers', []).controller('PostCtrl', ['$scope', 'postalService', function($scope, postalService) {
$scope.posts = [];
$scope.getPosts = function() {
postalService.getPosts(function(err, posts) {
if(err);
else $scope.posts = posts;
});
};
}]);
Here's my directive. I am unable to invoke onPost.
angular.module('myApp.directives', []).directive('compose', ['postalService', function(postalService) {
return {
restrict: 'E',
transclude: false,
replace: true,
scope: {
onPost: "&" //why will it not
},
templateUrl: "partials/components/compose-partial.html",
controller: function($scope, postalService) {
$scope.title = "";
$scope.content = "";
$scope.newPost = function() {
postalService.newPost($scope.title, $scope.content, function(err) {
if(err) console.log(err + ":(");
else {
console.log("Success getting posts.");
//why can I not invoke onPost()??
$scope.onPost();
}
});
};
},
};
}]);
And here's the relevant part of my html
<div ng-controller="PostCtrl">
<section class="side-bar panel hide-for-small">
<compose onPost="getPosts()"></compose>
</section>
<!--more, non-relevant html here-->
</div>
I know the problem is not with my postalService Service. Instead, the directive reports that no function is passed to it. Why??
Replace
<compose onPost="getPosts()"></compose>
with
<compose on-post="getPosts()"></compose>
and it'll work.
The Angular docs say why it's so:
Directives have camel cased names such as ngBind. The directive can be
invoked by translating the camel case name into snake case with these
special characters :, -, or _.
When I generate a new element through a string that has a directive (that's why I need to compile) and that directive generates an association with a variable in the controller scope through "=", the variable in my controller isn't associated to the one in the directive.
I created a jsfiddle to show the example where the "door" ng-model value should be associated to all the directives model values.
See this fiddle: http://jsfiddle.net/aVJqU/2/
Another thing I notice is that the directive that run from elements present in the html show the correct association through the variables (controller and directive).
The html (there is the directive that binds <door>):
<body ng-app="animateApp">
<div ng-controller="tst">
<h2> Controller with its model </h2>
<input ng-model="doorval" type="text"> </input>
{{doorval}}
<h2> Directive render directly from the html </h2>
<door doorvalue="doorval"></door> <key></key>
<h2> Directives that are compiled </h2>
<list-actions actions="actions"></list-actions>
</div>
</body>
This is the directive:
animateAppModule.directive('door', function () {
return {
restrict: "E",
scope: {
doorvalue:"="
},
template: '<span>Open the door <input type="text" ng-model="doorvalue"> </input> {{doorvalue}}</span>',
replace: true
}
})
This is the controller:
var animateAppModule = angular.module('animateApp', [])
animateAppModule.controller('tst', function ($scope, tmplService) {
$scope.doorval = "open"
$scope.actions = tmplService;
})
animateAppModule.service('tmplService', function () {
return [{
form_layout: '<door doorvalue="doorval"></door> <key></key>'
}, {
form_layout: '<door doorvalue="doorval"></door> with this <key></key>'
}]
})
And finally this is the directive that compiles the string that has the directive that doesn't bind:
animateAppModule.directive('listActions', function ($compile) {
return {
restrict: "E",
replace: true,
template: '<ul></ul>',
scope: {
actions: '='
},
link: function (scope, iElement, iAttrs) {
scope.$watch('actions', function (neww, old,scope) {
var _actions = scope.actions;
for (var i = 0; i < _actions.length; i++) {
//iElement.append('<li>'+ _actions[i].form_layout + '</li>');
//$compile(iElement.contents())(scope)
iElement.append($compile('<li>' + _actions[i].form_layout + '</li>')(scope))
}
})
}
}
})
What can I do to bind all the "door" ng-model values together?
Where is the compiled directive binding to?
You just have to pass the doorval reference down through all directives without skip any one. The problem was the listActions directive didn't had access to doorval in its scope.
Check this out: http://jsfiddle.net/aVJqU/5/
#Danypype is basically correct as the problem occurs due to scope isolation, as explained in the documentation.
An alternative solution is to simply eliminate the scope isolation by removing the scope block from within the directive definition.