ng-model returning 'undefined' from directive - javascript

I am trying to implement a system of reddit-like nested comments with reply fields hidden with ng-show.
However when I attempt to return the comment from a custom directive into the controller, the result is always 'undefined'.
I've followed this tutorial:
How to get the form data when the form is in a directive in Angular?
but it's not working for me.
app.directive("replyContainer", function() {
return {
restrict: "E",
scope: {
onSubmit: "&"
},
template: '<a ng-click="replyForm = !replyForm">reply</a>' +
'<div ng-show="replyForm" id="replyForm">' +
'<form ng-submit="submit()" ng-transclude'+
'ng-show="isLoggedIn()"'+
'style="margin-top:30px;">'+
'<h3>Reply</h3>'+
'<div class="form-group">'+
'<input type="text" '+
'class="form-control"'+
'placeholder="Comment"'+
'parent="{{comment._id}}"'+
'<script>console.log(parent)</script>'
'ng-model="model.Name"></input>'+
'</div>'+
'<button ng-click="submit()"'+
'class="btn btn-primary">Reply</button>'+
'</form>'+
'</div>',
transclude: true,
link: function(scope, element, attributes) {
scope.submit = function() {
scope.onSubmit();
}
}
}
})
app.controller('PostsCtrl', ['$scope', 'posts', 'post', 'auth',
function($scope, posts, post, auth) {
$scope.model = {};
$scope.submittedValue = null;
$scope.post = post;
$scope.isLoggedIn = auth.isLoggedIn;
$scope.replyForm = false;
$scope.addReply = function (){
$scope.submittedValue = $scope.model.Name;
console.log($scope.parent);
};
index.ejs:
<reply-container on-submit="addReply()"></reply-container>

Related

AngularJS =?bind not updating

I've lost my bearings with regards to why I can't pass updates to my directives.
What I'm trying to accomplish with the following piece of code is to be able to set focus on by pressing a button. The problem is however that the "focus" binding on drInput only ever is set when the directive have loaded when it should change whenever it changes in drWrap. How come and how do I get around this?
And now, ladies and gentlemen, I present to you: THE CODE!
<div ng-app="myApp">
<dr-wrap></dr-wrap>
</div>
var myApp = angular.module('myApp', []);
myApp.directive('drWrap', function($timeout) {
return {
scope: {
focus: '=?bind'
},
restrict: 'E',
replace: 'true',
template: '<div><button ng-click="openSearch()">focus</button><dr-input focus="focusSearch" /></div>',
link: function(scope, elem, attr){
scope.openSearch = function(){
$timeout(function(){
scope.focusSearch = true
alert('scope.focusSearch 2 = ' + scope.focusSearch)
}, 1000)
}
}
};
})
.directive('drInput', function() {
return {
scope: {
focus: '=?bind'
},
restrict: 'E',
replace: 'true',
template: '<input type="test" focus-me="{{ focus }}" />',
link: function(scope, elem, attr){
scope.$watch('focus', function(value){
if(value != undefined){
scope.focus = value
alert('scope.focus = ' + scope.focus)
}
})
}
};
})
.directive('focusMe', ['$timeout', function ($timeout) {
return {
link: function (scope, element, attrs) {
attrs.$observe('focusMe', function(value){
if ((value === true) || (value == 'true')) {
$timeout(function () {
element[0].focus()
scroll(element[0])
})
} else {
element[0].blur()
}
})
}
}
}])
And the FIDDLE!
https://jsfiddle.net/L56rdqLp/168/
When you write scope: { focus: '=?bind' }, this means that the attribute name should be bind but not focus, so the template of drWrap should look like:
template: '<div><button ng-click="openSearch()">focus</button><dr-input bind="focusSearch" /></div>'
Add ngBlur event handler to drInput directives input like:
template: '<input type="test" focus-me="{{ focus }}" ng-blur="focus = false"/>',
to change the model to false, when input has lost its focus.
Here is working fiddle.

Passing the value in directive to the ng-model. -angularjs

Hi Im trying to create a directive to pass some value to my ng-model,
in my directive i have a controller inside my directive and and i want to pass the value of it in my ng-model
Lets just say i have a string value, when i click the $scope.speakUP it should be pass it on the ng-model
.directive('speak', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: true,
template: '<i ng-click = "speakUP()" class="icon ion-mic-a larger"></i>',
controller: function($scope, $element){
$scope.speakUP = function(){
$scope.passThisString = "Sample Data";
}
}
This is my HTML
<input type="text" ng-model="sampleModel" speak>
this is a quick example from where you can start implement your goals.
app.directive('inputField', function () {
return {
require: '?ngModel',
template: '<input ng-model="value" ng-change="onChange()"><i ng-click="speakUP()" class="icon ion-mic-a larger">click</i>',
link: function ($scope, $element, $attrs, ngModel) {
if (!ngModel) return;
$scope.speakUP = function(){
ngModel.$setViewValue('your data');
ngModel.$render();
}
$scope.onChange = function() {
ngModel.$setViewValue($scope.value);
};
ngModel.$render = function() {
$scope.value = ngModel.$modelValue;
};
}
};
});
HTML
<input-field name="sampleModel" ng-model="sampleModel"></input-field>

Modify ng-show within directive template from link

I have a directive element:
return {
restrict: 'E',
replace: true,
transclude: true,
template: '<ul>' +
'<li ng-show="hideItem">Home</li>' +
'<li ng-show="hideItem">Products</li>' +
'<li ng-show="!hideItem">Cart</li>' +
'<li ng-show="hideItem">Contact Us</li>' +
'</ul>',
link: function(scope, element, attrs) {
var shouldHide = myService.getData();
if (shouldHide === true) {
scope.hideItem = true
}
}
};
The link function performs a call to a service, the result is either true or false.
If true, i want hideItem to be set to true within my ng-show.
HTML structure:
<section ng-controller="NavigationController">
<i class="home"></i>
<i class="bell"></i>
<i class="phone"></i>
<my-directive></my-directive>
<button>Submit</button>
</section>
DEMO
you can actually just vm.hideItem = myService.getData(); since you want the boolean's value anyway
return {
restrict: 'E',
replace: true,
controllerAs: 'vm',
transclude: true,
template: '<ul>' +
'<li ng-show="vm.hideItem">Home</li>' +
'<li ng-show="vm.hideItem">Products</li>' +
'<li ng-show="!vm.hideItem">Cart</li>' +
'<li ng-show="vm.hideItem">Contact Us</li>' +
'</ul>',
link: function(scope, element, attrs, vm) {
vm.hideItem = myService.getData();
},
controller: function(){
}
};
I added controllerAs: 'vm' it's much more manageable by assigning a name to your controller and attach variables to it
You have to watch it :
scope.$watch(function(){
return myService.getData();
}, function(newValue){
scope.hideItem = newValue;
});
This is only if your service is not doing server-side requests, otherwise you'll spam the server.
I think getData method can be called from anywhere in your application.
And you want to keep track of these changes in your directive. In this case, you can use the callback.
Live example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, myService) {
$scope.resolve = function() {
myService.getData().then(function() {
console.log('resolved from button resolve');
})
}
myService.getData().then(function() {
console.log('resolved from controller loading');
})
})
.directive('exampleDirective', function(myService) {
return {
restrict: "E",
scope: {
value: "="
},
template: `<div>hidden={{hidden}} value={{value}} <span ng-show="hidden">ng-show="hidden"</span><span ng-show="!hidden">ng-show="!hidden"</span></div>`,
link: function(scope) {
scope.hidden = false;
myService.addCallback(function(hideItem) {
scope.hidden = hideItem;
console.log('callback resolved with value ' + scope.value + ' and hide is ' + hideItem);
});
}
}
})
.service('myService', function($q, $timeout) {
var callbacks = [];
return {
getData: function() {
var defered = $q.defer();
//simulate $http call
$timeout(function() {
defered.resolve();
//simulate answer from server
var res = Math.round(Math.random() * 10) >= 5;
angular.forEach(callbacks, function(c) {
//call callback with result
$q.resolve(res, c);
});
}, 1000);
return defered.promise;
},
addCallback: function(callback) {
callbacks.push(callback);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController" id="ExampleController">
<button ng-click="resolve()">
call getData
</button>
<example-directive value="12"></example-directive>
<example-directive value="'ab'"></example-directive>
</div>
</div>
When you anywhere using the method of your getData directive knows that.

AngularJS: render HTML in directive controller

I'm writing a directive for creating text from templates, but I cannot get to render my final result into HTML. This is the directive:
.directive('description', function($timeout){
function descriptionCtrl(){
var self = this;
self.result = "";
self.init = function(value) {
console.log("template in directive",value);
self.finalValue = "<div>HI <input type='text' id='hi' /></div>";
};
}
return {
restrict: 'AE',
controller : descriptionCtrl,
controllerAs: 'dc',
scope: {
text: "="
},
replace: true,
template: "<div id='template'>{{dc.finalValue}}</div>",
link: function(scope, iElement, iAttrs, ctrl) {
scope.$watch("text", function(value){
if(value!==undefined){
$timeout(ctrl.init(value),0);
}
});
}
}
});
The data comes from the controller and once the user has chosen between some options, hence the $watch.
Thank you!
You should use ng-bind-html to bind html to the div
template: "<div id='template' ng-bind-html='dc.finalValue'></div>",

Initialize text input fields in angular directive

I have a directive which shows input fields and I want to initialize those fields with data from the server. The problem is that I can't do that while using ng-model.
Before using a directive I used in the controller something like $scope.field1 = $scope.first.field1
Here's my code. I simplified it for the sake of readability but the idea's here.
In my controller I have this code:
app.controller('MyController',
['$scope', 'myData', function($scope, myData) {
myData.then(function(data) {
$scope.first = data.first;
$scope.second = data.second;
});
}]);
Inside first and second I have 2 field: field1 and field2.
In in html code, I have this bit:
<h1>First</h1>
<my-directive info="first"></my-directive>
<h1>Second</h1>
<my-directive info="second"></my-directive>
The directive is as follows:
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'static/js/myDirective.html',
link: function(scope, element, attrs) {
scope.doStuff = function() {
/* Do stuff with
scope.field1 and scope.field2 */
}
}
};
});
and the myDirective.html code:
<input type="text" ng-model="myfield1" />
<input type="text" ng-model="myfield2" />
<input type="submit" ng-click="doStuff()" />
If in myDirective.html I write:
<input type="text" value="info.field1" />
I can see the value fine.
Any ideas?
probably your directive initializes before your data loads. and your directive sees ng-model as an undefined variable. You are not using info directly in template so no auto $watch's for you :).
you need to $watch your info variable in directive and call your doStuff function on change.
note: i wouldn't recommend adding a controller to a directive just for this task. adding a controller to a directive is needed when you need to communicate with other directives. not for waiting async data
edit
you should do
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl: 'static/js/myDirective.html',
link: function(scope, element, attrs) {
scope.doStuff = function() {
/* Do stuff with
scope.field1 and scope.field2 */
}
scope.$watch('info', function(newValue){
scope.doStuff();
});
}
};
});
Check working demo: JSFiddle.
Define a controller for the directive and do the initialization inside it:
app.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
controller: ['$scope', 'myData', function ($scope, myData) {
myData.then(function(data){
$scope.first = data.first;
$scope.second = data.second;
});
}],
...
},
Inside the directive, myfield1 and myfield2 don't exist. You are close to solving the issue by using info.field1 instead.
var myApp = angular.module('myApp', []);
//Faking myData here; in your example this would come from the server
var myData = {
first: {
field1: "FirstField1",
field2: "FirstField2"
},
second: {
field1: "SecondField1",
field2: "SecondField2"
}
};
myApp.controller('MyController', ['$scope', function($scope) {
$scope.first = myData.first;
$scope.second = myData.second;
}]);
myApp.directive('myDirective', function() {
return {
restrict: 'E',
scope: {
info: '='
},
template: '<input type="text" ng-model="info.field1" /><input type="text" ng-model="info.field2" /><input type="submit" ng-click="doStuff()" />',
link: function(scope, element, attrs) {
scope.doStuff = function() {
alert('Info: ' + scope.info.field1 + ', ' + scope.info.field2);
}
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<h1>First</h1>
<my-directive info="first"></my-directive>
<h1>Second</h1>
<my-directive info="second"></my-directive>
</div>

Categories

Resources