AngularJs passing parameter values to controller - javascript

My Html:
<test-app email="hello#hotmail.com"></test-app>
My Directive:
.directive('testApp', function () {
return {
restrict: 'E',
scope: {
userEmail = '#userEmail'
},
templateUrl: 'Form.html'
};
})
My Form in another Page:
<label> Email </label>
<input type="text" id="email">
Issue: I need to get the parameter value , and print it out on the textbox itself.
What i have done: I research on a lot of articles which demonstrated on how to pass directive parameters to controller but they were very complicated.
What i think is the next step:
1) Pass the directive parameter to the controller and then bind the controller to the textbox and set the value of the textbox to be the parameter value.
2) Or is there another way i can do this?
I am stuck on how to proceed on.

You can use attribute string binding using #
In controller you initialize your userEmail variable
The directive has a user-email attribute which loads value into the directive's userEmail local scope variable.
Using userEmail:'#' allows for string binding from controller to the directive.
See demo below:
angular.module("app",[]).directive('application', function() {
return {
restrict: 'E',
scope: {
userEmail : '#'
},
templateUrl: 'Form.html'
};
}).controller("ctrl",function($scope){
$scope.userEmail="hello#hotmail.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<application user-email="{{userEmail}}"></application>
<script type="text/ng-template" id="Form.html">
<label>Email</label>
<input type="text" id="email" ng-model="userEmail">
</script>
</div>

Related

AngularJs Bind Directive parameter to mdDialog's Form

Hi guys I have a very complicated issue.
I have created a reusable directive and now i want to take the user's parameter value and bind it to my form inside the directive.
At the user's side, they are able to call the directive by:
<test-app></test-app>
Then they are able to pass in parameters into the directive :
<test-app user-email="test#hotmail.com"></test-app>
OR
<test-app user-email="{{ userEmail }} "></test-app>
//They can take value from their own controller.
At my Own side at the directive , main.js :
angular.module('TestModule').controller('MainCtrl',['$mdDialog',function($mdDialog) {
this.openDialog = openDialog;
function openDialog(){
$mdDialog.show({
controller: 'DialogCtrl as dialog',
templateUrl: 'dialog.html'
});
}
}]);
angular.module('TestModule').directive('testApp',function(){
return {
controller: 'MainCtrl as main',
scope: {
userEmail :'#'
},
restrict : 'E' ,
templateUrl : 'FormButton.html'
}
});
angular.module('TestModule').controller('DialogCtrl',['$mdDialog',function($mdDialog,$scope){
function submit(){
etc etc . .
}
}
At the FormButton.html:
<md-button ng-click="main.openDialog()"> </md-button>
At the dialog.html:
<md-dialog>
<form>
etc , etc
<input type="email" name="email" placeholder="Email" data-ng-model="userEmail">
etc , etc
</form>
</md-dialog>
Issue: I need to pass in the userEmail value from the user side and bind it to the form so that when the user opens the form , the value is there.
I think because of the templateUrl , the convention way of binding the model doesn't work.
What i have tried:
1) I tried ng-model to bind but the form is in another page so it was not able to read the value.
2) I wanted to pass the value from the directive to controller , I research online but found no viable solution to this problem.
can anyone Kindly Help with this solution?
Take a look at the $mdDialog api docs, especially at the locals option.
locals - {object=}: An object containing key/value pairs. The keys
will be used as names of values to inject into the controller. For
example,
this.userEmail = 'someone#neeae.com';
function openDialog(){
$mdDialog.show({
controller: 'DialogCtrl as dialog',
templateUrl: 'dialog.html',
locals: {
email: this.userEmail // `this` is the main controller (parent).
}
});
}
In the html:
<test-app user-email="{{ main.userEmail }} "></test-app>
DialogCtrl
angular.module('TestModule').controller('DialogCtrl', ['$mdDialog', '$scope', 'email', function($mdDialog, $scope, email) {
// Here you can use the user's email
this.userEmail = email;
function submit() {
//etc etc ..
}
}]);
At the dialog.html:
<md-dialog>
<form>
<!-- etc , etc-->
<input type="email" name="email" placeholder="Email" data-ng-model="dialog.userEmail">
<test-app email="test#hotmail.com"></test-app>
You are passing value in "email" variable. But you are not mapping this variable in directive scope.
Try this once.
<test-app userEmail="test#hotmail.com"></test-app>

Passing custom directive attribute to ng-model in template

I'm trying to pass in some attributes to my <custom-input> directive. Like so...
<custom-input type="text" name="first_name" title="First Name"></custom-input>
However, I'm getting a syntax error for the line where I pass the attribute to ng-model in the template.
I'm not sure what I'm doing wrong? Everything was working before I tried to move into a custom directive.
Directive
.directive('customInput', function() {
return {
restrict: 'E',
scope: {
type: '#type',
name: '#name',
title: '#title'
},
templateUrl: './assets/templates/custom-input.html',
controller: function() {
this.data = {}
this.focus = null;
},
controllerAs: 'input'
};
})
Template
<div class="Form__field">
<input
ng-model="input.data.{{name}}"
ng-class="{'Form__input--is-filled': input.data.{{name}}.length > 0}"
ng-focus="input.focus='{{name}}'"
ng-blur="input.focus=null"
class="Form__input"
type="{{type}}"
name="{{name}}"
placeholder="{{title}}"
/>
<label
ng-show="input.data.{{name}}.length > 0"
ng-class="{'Form__label--is-active': input.focus === '{{name}}'}"
class="Form__label"
for="{{name}}"
>{{title}}</label>
<div
class="Info Info--default"
ng-show="input.focus === '{{name}}'">
</div>
</div>
Error
Error: [$parse:syntax] Syntax Error: Token '{' is not a valid
identifier at column 12 of the expression [input.data.{{name}}]
starting at [{{name}}].
Before:
input.data.{{name}}
After:
input.data[name]
Your inner scope is getting type, name, and title attached directly to it. By defining the scope in the directive definition, you are declaring an isolate scope--one that no longer has access to the outer scope. You're also not passing in your input object.
What you have is the same as doing this inside the controller:
scope.name = 'first_name';
scope.title = 'First Name';
scope.type = 'text';
If you follow #bchemy's suggestion, you'll get a new property on your empty input.data object called first_name. And then the contents of the input would go into that. But there's no reason to expect that anything will come into it, because you didn't pass anything in that you're putting into that variable.

How to get parameter on ngClick. And then, triggered the directive to injected dinamically template

I need to inject new template dynamically depending on the value or parameter of radio button.
This is my HTML
<div class="container-fluid" ng-app="rjApp">
<div class="panel-body" ng-controller="mainController">
<input name="penanggung_biaya" type="radio" ng-model="checked" ng-click="broadcast(umum)" class="ace" value="umum"> <!-- I though, umum is the parameter which I want passed through to the Controller -->
<input name="penanggung_biaya" type="radio" ng-model="checked" ng-click="broadcast(instansi)" class="ace" value="instansi">
<example-directive message="message"> </example-directive>
</div>
</div>
and, this is the JS
var rjApp = angular.module('rjApp',[]);
rjApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{::');
$interpolateProvider.endSymbol('::}');
})
//mainCotroller, should be work by ngClick through radio button
function mainController($scope, $rootScope) {
$scope.broadcast = function(event){
console.log(event) //I've been thought, this is the part to passing the parameter of radio button, but not gonna works.
$rootScope.$broadcast('handleBroadcast');
};
}
//the Directive, should be injected dinamically template, depends on ngClick parameter inside radion button
rjApp.directive('exampleDirective', function() {
return {
restrict: 'E',
scope: {
message: '='
},
link: function(scope, elm, attrs) {
scope.$on('handleBroadcast', function(doifq) {
templateUrl= '<?php echo url("registrasi/rawat_jalan/penanggung_biaya/") ?>'+doifq //This is the part to injected the dinamically template. And I've been guess the **doifq**, is the paramter to passing by the mainController
});
},
};
});
Please, somebody help me.
Regards.
In broadcast, you could pass the parameter,
$scope.broadcast = function(event){
console.log(event);
$rootScope.$broadcast('handleBroadcast',event);
};
This way you would be getting doifq value in directive depending on the which radio button is clicked.

Angularjs Pass all attributes on a directive to the view

I'm building a tiny angular directive <my-input> on top of a normal HTML <input>.
And because this is going to be available in a framework, I need to allow people to pass whichever attribute they might use from the directive to the input element. For example:
<my-directive disabled="disabled" type="email">
would render
<input disabled="disabled" type="email">
I know that if I have a static list of attributes, I can manually do it.. but the problem is I can't predict what attributes will be added.. so I'm looking for a solution that passes all the attributes from the directive to the input element.
Thanks
If you want to pass multiple attributes to the view, you can perform it into the link function.
Here is your directive :
Directive
(function(){
function myInput($compile) {
return{
restrict: 'E',
templateUrl: 'template.html',
link: function(scope, elm, attrs){
//Convert camelCase to dash
function toDash(str) {
return str.replace(/\W+/g, '-')
.replace(/([a-z\d])([A-Z])/g, '$1-$2');
}
//Retrieve input into the template
var input = angular.element(document.querySelector('#myInput'));
//Loop on attrs
for (var key in attrs) {
if (key[0] !== '$'){
//Remove all attribute to the top level element
elm.removeAttr(toDash(key));
//Add our attribute to the input
input.attr(toDash(key), attrs[key]);
//Compile and link it to the scope
$compile(input)(scope);
}
}
}
};
}
angular
.module('app')
.directive('myInput', myInput);
})();
With the template :
template.html
<input type="text" id="myInput">
For example, in a controller you can set some variable :
Controller
(function(){
function Controller($scope) {
$scope.show = true;
$scope.toto = 'Hello !!'
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
And call your directive :
<body ng-app="app" ng-controller="ctrl">
<my-input disabled="disabled" ng-model="toto" ng-show="show"></my-input>
</body>
So it will remove all attributes to the my-input element, and set it into your template.

Problems with angular validation in directive

I am fighting with the validation in an angular directive without success.
The form.name.$error object seems to be undefined, when I submit the name property to the directive template. If i use a fixed name-attribute inside the template, the $error object is fine, but of course identical for all elements.
The html is:
<form name="form" novalidate>
<p>
<testvalidation2 name="field1" form="form" field="testfield4" required="true">
</testvalidation2>
</p>
</form>
The directive looks like this:
app.directive('testvalidation2', function(){
return {
restrict: 'E',
scope: {
ngModel: '=',
newfield: '=field',
required: '=required',
form: '='
},
templateUrl: 'template2.html',
link: function(scope, element, attr){
scope.pattern = /\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/;
scope.name = attr.name;
}
} // return
});`
and finally the template:
<div>
<input name="{{name}}" type="text" ng-model="newfield" ng-required="required" ng-pattern="pattern"> {{FIELD}}</input>
<span ng-show="form.name.$error.required">Required</span>
<span ng-show="form.name.$error.pattern"> Invalid </span>
<p>Output {{form.name.$error | json}}</p>
</div>
I have created a plunker for my Angular Validation Problem
and would be happy, if someone would help me to win the fight.
Michael
I don't have a fix for this but I can tell you what the problem is.
Firstly in your html form="form" should have name of the form form="form2".
Secondly Since you are creating a new scope in the directive, the scope created is a isolated scope which does not inherit from parent, which means that the the template input control that you add would not get added to the parent scope form2.
The only way out currently i can think of is to not use isolated scope.

Categories

Resources