Angular directive controller scope visibility - angularjs

Question
Why isn't monkey and selected visible to the template?
Plunk
http://plnkr.co/edit/djS0KWyfJNKD0tfZ0IiV?p=preview
Code
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
<script type="text/javascript">
angular
.module('toruSelect', [])
.directive('toruSelect', function () {
return {
restrict: 'AE', // Allow usage as A - attribute, E - element
scope: { // Isolated scope
selected: '=' // Bi-directional binding to selected attribute,
},
controller: ['$scope', function ($scope) {
$scope.monkey = 'MONKEY';
console.log('toruSelect.controller.$scope', $scope);
}]
}
});
var app = angular.module('app', ['toruSelect']);
app.controller('AppCtrl', function($scope) {
$scope.val = 'initial';
$scope.appData = 'App data';
});
</script>
</head>
<body ng-controller="AppCtrl">
<h1>Directives and scopes..</h1>
<div toru-select selected="val">
<div style="color: red">RESULT: toruSelect.controller.monkey: {{monkey}}</div>
<div>EXPECTED: toruSelect.controller.monkey: MONKEY</div>
<div style="color: red">RESULT: toruSelect.controller.selected: {{selected}}</div>
<div>EXPECTED: toruSelect.controller.selected: initial</div>
</div>
</body>
Result
Directives and scopes..
RESULT: toruSelect.controller.monkey:
EXPECTED: toruSelect.controller.monkey: MONKEY
RESULT: toruSelect.controller.selected:
EXPECTED: toruSelect.controller.selected: initial

As you pointed it out on the comment of your directive, it has an isolated scope, so that value attached with monkey key is available on directive scope, not on controller one.
For selected, you have to display {{val}} and not {{selected}} as it's the variable concerned by the bi-directional binding on the directive scope.

Related

angularjs dom manipulation based on button click

basically i want to change the attribute value based on the button i clicked,
these are the two buttons
<button ng-click="fn(a)"></button>
<button ng-click="fn(b)"></button>
and then i have a prebuilt directive who takes value as input,
<div directive-name="" id="abc"></div>
if i click on first button,i want the value of directive based on button clicked.
What i did earlier;
$scope.go = function(data){
if(data==a){
var b = document.querySelector( 'div' );
b.setAttribute("directive-name","value");
}
else{}
}
here the problem is that it is selecting the first div of document and setting attribute value for that.
I also tried to pass it with id like
var b = angular.element(document.querySelector('#abc'));
I also saw some custom directives to do so, but they are not working
AngularJS DOM Manipulation through Directives
If possible provide me a demo in plunkr or fiddle
and also if i want to change css property of div based on button clicked
Thanks in advance
You can do it like this.
Assign the directive-name value to a $scope.variable and then use variable as the value in HTML.
HTML - 1:
<button ng-click="go(a)"></button>
<button ng-click="go(b)"></button>
HTML - 2:
<div directive-name="{{directive}}" id="abc"></div>
JS:
$scope.go = function(data){
if(data==a){
$scope.directive = "directive-1";
}else if(data==b){
$scope.directive = "directive-2";
}
}
To assign class name to div you can define other $scope.classVar and then use that in HTML like below:
<div directive-name="{{directive}}" id="abc" ng-class="classVar"></div>
I hope this will solve your problem.
This should work, (you had some errors in your code):-
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.fn = function(data,id) {
if (data == 'a') {
var b = document.querySelector('#'+id);
b.setAttribute("directive-name", "value");
} else {
}
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div directive-name="" id="abc"></div>
<button ng-click="fn('a','abc')">A</button>
</div>
"Basically I want to change the attribute value based on the button I clicked."
You can do this by changing the attribute value the angular way, referencing a property of $scope or the controller instance in your template. When clicking a button, set the variable to the value you require to be passed to your directive.
Note: When you pass a value into your ngClick directive, you need to pass it as a string unless a and b are declared as properties of $scope.
Here's a basic example:
// app.js
(function() {
'use strict';
angular.module('app', []);
})();
// main.controller.js
(function() {
'use strict';
angular.module('app').controller('MainController', MainController);
MainController.$inject = ['$scope'];
function MainController($scope) {
$scope.fn = fn;
function fn(data) {
// set the value so it's accessable in the view
// therefore we can pass it into our directive
$scope.myVar = data;
}
}
})();
// directive-name.directive.js
(function() {
'use strict';
angular.module('app').directive('directiveName', directiveNameDirective);
function directiveNameDirective() {
return {
restrict: 'A',
scope: {
directiveName: '='
},
template: '<span>directiveName: {{ directiveName }}</span>'
};
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainController as MainCtrl">
<!-- here we pass a and b as strings otherwise they get evaluated as variables -->
<button ng-click="fn('a')">Set a</button>
<button ng-click="fn('b')">Set b</button>
<hr>
<!-- here we pass myVar which is declared as a property of $scope when the fn function is called -->
<div directive-name="myVar" id="abc"></div>
<hr> myVar: {{ myVar }}
</div>
</div>

How to control invoking of directive

In this plnkr :
https://plnkr.co/edit/F0XsOPZKq5HArFo9vtFs?p=preview
I'm attempting to prevent a custom directive being invoked by the use of ng-show. But if check console output when the directive is invoked 4 times : console.log('invoked') But ng-show shows/hides html elements it does not control what is rendered within the custom directive itself.
Is there a mechanism to pass the ng-show to the custom directive and if it's false then do call the directive ? I think could pass a new variable to the directive which contains same value as ng-show and then wrap the body of the directive in a conditional ?
src :
goob.html :
goob
http-hello2.html:
2. http-hello2.html
index.html :
<!doctype html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="FetchCtrl">
<label>Filter: <input ng-model="search"></label>
<div ng-show="false">
<div ng-repeat="sourceUrl in sourceUrls | filter:search track by $index ">
<status-viewer url="sourceUrl"> </status-viewer>
</div>
</div>
</div>
</body>
</html>
mytemplate.html :
<!--<h1>{{url}}</h1>-->
<div>
<p>{{model}}</p>
</div>
script.js :
var myapp = angular.module('app', []).controller('FetchCtrl', FetchCtrl)
myapp.directive('statusViewer', function ($http , $interval) {
return {
restrict: 'E',
templateUrl: 'mytemplate.html',
scope: {
url: '='
},
link: function (scope, elem, attrs, ctrl) {
console.log('invoked')
scope.isFinishedLoading = false;
$http.get(scope.url).success(function (data) {
scope.model = data;
});
}
};
});
function FetchCtrl($scope, $http, $q , $parse) {
$scope.sourceUrls = [
'http-hello2.html'
,'http-hello2.html'
,'test.html'
,'goob.html'];
}
test.html :
test
Instead of ng-show you should use ng-if directive to avoid directive linking before show
Forked plunker example

AngularJs directive to access the parent scope

I want to show the password fields based upon the condition. Also I want to validate the password fields if it is shown. For this I have to create a directive. But the directive creates new scope for the template and does not access the parent scope to validate the password fields. How could I achieve this?
You can send it through the DOM.
Send the data from the controller's scope and send that as an attribute to the directive you are creating.
angular.module('App', [])
.controller('Controller', ['$scope', function($scope) {
$scope.data = ....;
}])
.directive('myDirective', function() {
return {
scope: { info = '=info' },
template: '<div ng-repeat="i in info"> Name: {{i.name}} Password: {{i.password}}</div>',
link: ...
}
});
<html>
<body ng-app="App">
<div ng-controller="Controller">
<my-directive info="data"></my-directive>
</div>
</body>
</html>

Angular directive referencing wrong element

I have an issue where a directive i'm using for several similar elements in an ng repeat is showing the wrong element when calling the keyup function.
plunker: http://plnkr.co/edit/ARFlsgPdxikpzLScztxU?p=preview
Here's the same code:
html
<body ng-app="app">
<section ng-controller="MainController" ng-repeat="item in list">
<div ng-repeat="item in list">
<h3>Item {{$index}}</h3>
<div class="aliasContainer">
<input text="text" obj-key="alias" value="{{item.alias}}" ng-keyup="logItem($event, item)">
</div>
<div class="nameContainer">
<input text="text" obj-key="name" value="{{item.name}}" ng-keyup="logItem($event, item)">
</div>
</div>
</section>
<script src="https://code.angularjs.org/1.2.25/angular.js"></script>
<script src="script.js"></script>
</body>
js
var app = angular.module('app', []);
app.controller('MainController', ['$scope', function($scope){
console.log("hello ctrl");
$scope.list = [
{name: 'Dick Grayson', alias: 'Nightwing'},
{name: 'Bruce Wayne', alias: 'Batman'},
{name: 'Jason Todd', alias: 'Robin'}
];
}]);
app.directive('objKey', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.logItem = function($event, item) {
console.log(element);
};
}
};
});
The behavior the link function is exhibiting is for each div that is repeated, only the the input in the nameContainer gets passed on keyup (logging the element will show the input in nameContainer of the same parent div even if the input in aliasContainer was the triggering element.)
To reuse your directive and keeping its scope separate from outer scope (controller), you need to have a isolate scope to your directive
app.directive('objKey', function() {
return {
restrict: 'A',
scope: true, // << Isolating scope
link: ....
}
};
You should look into directive's scope: https://docs.angularjs.org/guide/directive
If you don't isolate the scope, your directive's scope will be the same as the scope when it's declared, in this case it will use the child scope created by ng-repeat.
To fix this, just isolate the scope with scope: true

AngularJS: Access formController of a form placed inside transcluded directive from parent controller

I've created a simple "modal dialog" directive, which uses transclude. I would like to place a form () inside the "modal dialog" directive. I would expect that formController of a form placed inside the directive, is going to be accessible in parent controller's scope, however it isn't. Take a look at the following fiddle, please: http://jsfiddle.net/milmly/f2WMT/1/
Complete code:
<!DOCTYPE html>
<html>
<head>
<title>AngJS test</title>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/foundation/4.0.9/css/foundation.min.css">
<style>
.reveal-modal {
display: block;
visibility: visible;
}
</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.1.4/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('appCtrl', function ($scope) {
$scope.model = {
id: 1, name: 'John'
};
$scope.modal = {
show: false
};
});
app.directive('modal', function () {
return {
scope: {
show: '='
},
transclude: true,
replace: true,
template: '<div class="reveal-modal small" ng-show="show"><div class="panel" ng-transclude></div></div>'
}
});
</script>
</head>
<body ng-app="app">
<div ng-controller="appCtrl">
<div class="panel">
Id: {{ model.id }}<br>
Name: {{ model.name }}<br>
Controller formController: {{ form }}<br>
Directive formController: {{ myForm }}<br>
</div>
<form name="form" class="panel">
<input type="text" ng-model="model.name">
</form>
<a ng-click="modal.show=!modal.show">toggle dialog</a>
<div modal show="modal.show">
<form name="myForm">
<input type="text" ng-model="model.name">
</form>
</div>
</div>
</body>
</html>
So my question is how to access or is it possible to access directive's formController from parent controller?
Thank you for answers.
-Milan
Because you are using transclude, the directive will create a child transcluded scope. There is no easy path from the controller scope (003) to the directive's transcluded scope (005):
(The hard/not recommended path is to go via private property $$childHead on the controller scope, find the isolate scope, then use $$nextSibling to get to the transcluded scope.)
Update:
From insights from this answer, I think we can get the formController inside the directive, then use = to get it to the parent.
scope: { show: '=', formCtrl: '=' },
...
link: function(scope, element) {
var input1 = element.find('input').eq(0);
scope.formCtrl = input1.controller('form');
}
HTML:
<div modal show="modal.show" form-ctrl="formCtrl">
Fiddle
Here is my solution:
I create such method in parent controller :
$scope.saveForm = function(form) {
$scope.myForm = form;
};
Then I call it in transcluded content:
<my-directive>
<form name="myForm">
<div ng-init="saveForm(myForm)"></div>
</form>
</my-directive>
After creating directive instance i have form controller instance in parent scope.

Resources