Directive and scope in AngularJS - angularjs

Here is the code, ideally i should see
parent: true
when I click the toggle
However, it doesn't work
Here is the plunker
<body ng-controller="MainCtrl">
<button type="button" ng-click='isParentShown= !isParentShown' >Toggle</button>
<div><span>Controller-isParentShown: {{isParentShown}}</span></div>
<parent isShown='isParentShown'></parent>
</body>
var app = angular.module('plunker', []).directive('parent',function(){
return {
restrict: 'E',
replace: true,
scope: {
isShown: '='
},
template: '<span>Parent: {{isShown}}</span>'
};
}).directive('child',function(){
return {
restrict: 'E',
replace: true,
template:'<span>Child: {{isChildShown}}</span>',
scope: {
isChildShown: '#'
}
};
});
app.controller('MainCtrl', function($scope) {
$scope.isParentShown = false;
});

The problem is in the casing of the attributes, if you define a isShown binding, it's expecting a is-shown or is:shown attribute. Here's the fixed plunker: http://plnkr.co/edit/UOigth

Related

AngularJS $emit.$on query

Plunker is here:-
http://plnkr.co/edit/JaEi7ftnokYhdvBn4fRh?p=preview
I have emitted data and its available in $on() under data.name.
However, I am not able to display $scope.dumbevent1_name in UI using {{ dumbevent1_name }}
What am I doing wrong ?
Code:-
// Code goes here
angular.module('myapp', [])
.controller('mycontroller', mycontroller)
.component('semantic3', { // semantic3
restrict: 'E',
transclude: true,
template: `<h6> imsemantic3</h6> <div ng-transclude></div>
`,
controller: semantic3Controller,
})
.component('semantic2', { // semantic2
scope: {},
restrict: 'E',
transclude: true,
template: `<h6> imsemantic2</h6> <div ng-transclude></div>
`,
})
.component('semantic1', { // semantic1
scope: {},
restrict: 'E',
transclude: true,
template: `<h6> imsemantic1</h6> <div ng-transclude></div>
`,
})
.component('dumbCompDisplayNames', {
scope:true,
restrict: 'E',
template: `<h6>h6dumb1</h6> {{$ctrl.names}}`,
bindings:{
names : '<' //one-way data binding
},
controller: dumbController,
});
function semantic3Controller($scope, $element, $attrs){
var self = $scope;
$scope.$on('dumbevent1', function(event, data){
console.log(data.name); //works. received.
self.dname = data.name;
$scope.dumbevent1_name = data.name; //works
// console.log($scope.dumbevent1_name); //works
// capturename( data); //works
});
// console.log($scope.dumbevent1_name); //doesnt work.
// function capturename(x){
// $scope.dumbevent1_name = x.name;
// console.log($scope.dumbevent1_name); //works
// }
}
function dumbController($scope, $element, $attrs){
// console.log($scope); //works. these r NOT positional injection
// console.log($element);
// console.log($attrs);
$scope.$emit('dumbevent1', {name: 'namedumb1'});
}
// main controller
function mycontroller(){
console.log('i am mycontroller');
}
The time wasted on commenting repeatedly is worthwhile somehow?? If don't have time to look at the plunker don't waste time commenting. Like I said I fixed the issue.

AngularJS values

How do I get the FirstName value in my directive?
<hello-World value="{{item.FirstName}}"> </hello-World>
app.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: 'true',
template: '<h3>Hello ??????</h3>'
};
});
To get values you need to use scope parameter in directive. Read more from directives here https://docs.angularjs.org/guide/directive
Check this example
angular.module('myApp', [])
.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: 'true',
template: '<h3>Hello {{value}}</h3>',
scope: {
value: '#'
},
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<hello-World value='World' />
</div>
app.directive('helloWorld', function() {
return {
restrict: 'AE',
replace: 'true',
template: '<h3>Hello {{value}}</h3>',
scope: {
value: '='
}
};
});

AngularJS directive: scope with named controller

I have the example below.
HTML:
<body ng-controller="MainCtrl as MgtCtrl">
<p>Hello {{MgtCtrl.name}}!</p>
<p>Result is {{MgtCtrl.result}}!</p>
<output-content data="MgtCtrl.name" result="MgtCtrl.result"></output-content>
</body>
JavaScript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var MgtCtrl = this;
MgtCtrl.name = 'World';
MgtCtrl.result = "no";
MgtCtrl.changeLabel = function() {
alert('changeLabel');
MgtCtrl.result = 'yes';
}
});
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
},
controller: 'MainCtrl',
controllerAs: 'MgtCtrl'
};
});
ouputContent.html:
<div>
{{data}}
<button ng-click="MgtCtrl.changeLabel()">Change</button>
</div>
Plunker is: http://plnkr.co/edit/BW8VDyCaRnRgxE8I9JJy
I would like the result to be 'yes' when I click on the 'Change' button.
It doesn't work because of the named controller.
Could you please explain to me how to write the directive to do so ?
Regards.
You never was binding the scope variables to the named controller in the directive.
You must add the attribute bindToController: true to the directive definition like this plunker:
http://plnkr.co/edit/2QdnkpeuTM6adG9KoyJT?p=preview
Directive code:
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
},
controller: 'MainCtrl',
controllerAs: 'MgtCtrl',
bindToController: true
};
});
This go to add the data and result binding to the respective directive controller.
I think in this case you don't need to specify controller in the directive.
app.directive('outputContent', function() {
return {
restrict: 'E',
replace: true,
templateUrl: 'outputContent.html',
scope: {
data: '=',
changeLabel: '&',
result: '='
}
};
});
Also html shoul be updated:
<body ng-controller="MainCtrl as MgtCtrl">
<p>Hello {{MgtCtrl.name}}!</p>
<p>Result is {{MgtCtrl.result}}!</p>
<output-content data="MgtCtrl.name" result="MgtCtrl.result" change-label="MgtCtrl.changeLabel()"></output-content>
</body>

AngularJS directives data binding doesn't work

DEMO
Here is a simplified version of the two directives I have, my-input and another-directive:
HTML:
<body ng-controller="AppCtrl">
<another-directive>
<my-input my-input-model="data.firstName"></my-input>
</another-directive>
</body>
JS:
.directive('myInput', function() {
return {
restrict: 'E',
replace: true,
scope: {
model: '=myInputModel'
},
template: '<input type="text" ng-model="model">'
};
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
scope: {},
compile: function(element) {
var html = element.html();
return function(scope) {
var output = angular.element(
'<div class="another-directive">' +
html +
'</div>'
);
$compile(output)(scope);
element.empty().append(output); // This line breaks the binding
};
}
};
});
As you can see in the demo, if I remove element.empty().append(output);, everything works fine, i.e. changes in the input field are reflected in controller's data. But, adding this line, breaks the binding.
Why is this happening?
PLAYGROUND HERE
The element.empty() call is destroying all child nodes of element. In this case, element is the html representation of another-directive. When you are calling .empty() on it, it is trying to destroy its child directive my-input and any scopes/data-bindings that go with it.
A somewhat unrelated note about your example. You should look into using transclusion to nest html within a directive, like you are doing with another-directive. You can find more info here: https://docs.angularjs.org/api/ng/service/$compile#transclusion
I think a little bit context as to what you are trying to do well be helpful. I am assuming you want to wrap the my-input directive in another-directive ( some sort of parent pane ). You could accomplish this using ng transclude. i.e
angular.module('App', []).controller('AppCtrl', function($scope) {
$scope.data = {
firstName: 'David'
};
$scope.test = "My test data";
}).directive('myInput', function() {
return {
restrict: 'E',
replace: true,
scope: {
model: '=myInputModel'
},
template: '<input type="text" ng-model="model">'
};
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
transclude: true,
scope: {},
template : '<div class="another-directive"><div ng-transclude></div></div>'
};
});
It works if you require ngModel
}).directive('anotherDirective', function($compile) {
return {
restrict: 'E',
require:'ngModel',
scope: {},
...

AngularJS - accessing parent directive properties from child directives

This should not be too hard a thing to do but I cannot figure out how best to do it.
I have a parent directive, like so:
directive('editableFieldset', function () {
return {
restrict: 'E',
scope: {
model: '='
},
replace: true,
transclude: true,
template: '
<div class="editable-fieldset" ng-click="edit()">
<div ng-transclude></div>
...
</div>',
controller: ['$scope', function ($scope) {
$scope.edit = ->
$scope.editing = true
// ...
]
};
});
And a child directive:
.directive('editableString', function () {
return {
restrict: 'E',
replace: true,
template: function (element, attrs) {
'<div>
<label>' + attrs.label + '</label>
<p>{{ model.' + attrs.field + ' }}</p>
...
</div>'
},
require: '^editableFieldset'
};
});
How can I easily access the model and editing properties of the parent directive from the child directive? In my link function I have access to the parent scope - should I use $watch to watch these properties?
Put together, what I'd like to have is:
<editable-fieldset model="myModel">
<editable-string label="Some Property" field="property"></editable-string>
<editable-string label="Some Property" field="property"></editable-string>
</editable-fieldset>
The idea is to have a set of fields displayed by default. If clicked on, they become inputs and can be edited.
Taking inspiration from this SO post, I've got a working solution here in this plunker.
I had to change quite a bit. I opted to have an isolated scope on the editableString as well because it was easier to bind in the correct values to the template. Otherwise, you are going to have to use compile or another method (like $transclude service).
Here is the result:
JS:
var myApp = angular.module('myApp', []);
myApp.controller('Ctrl', function($scope) {
$scope.myModel = { property1: 'hello1', property2: 'hello2' }
});
myApp.directive('editableFieldset', function () {
return {
restrict: 'E',
scope: {
model: '='
},
transclude: true,
replace: true,
template: '<div class="editable-fieldset" ng-click="edit()"><div ng-transclude></div></div>',
link: function(scope, element) {
scope.edit = function() {
scope.editing = true;
}
},
controller: ['$scope', function($scope) {
this.getModel = function() {
return $scope.model;
}
}]
};
});
myApp.directive('editableString', function () {
return {
restrict: 'E',
replace: true,
scope: {
label: '#',
field: '#'
},
template: '<div><label>{{ label }}</label><p>{{ model[field] }}</p></div>',
require: '^editableFieldset',
link: function(scope, element, attrs, ctrl) {
scope.model = ctrl.getModel();
}
};
});
HTML:
<body ng-controller="Ctrl">
<h1>Hello Plunker!</h1>
<editable-fieldset model="myModel">
<editable-string label="Some Property1:" field="property1"></editable-string>
<editable-string label="Some Property2:" field="property2"></editable-string>
</editable-fieldset>
</body>
You can get access to parent controller by passing attribute in child directive link function
link: function (scope, element, attrs, parentCtrl) {
parentCtrl.$scope.editing = true;
}

Resources