I need some help with getting AngularJS to maintain my non-string values in directive attributes.
I was looking for a way to render a tree structure in HTML from a piece of JSON, and I found this code: http://jsfiddle.net/n8dPm/
I've been trying to adapt that for my project, as shown in the code below.
My controller/directive is shown here:
cxpControllers.controller("ProductTocCtrl", ["$scope", "$http", "$routeParams",
function ProductTocController($scope, $http, $routeParams) {
$scope.typeOf = typeOf;
//test value
$scope.contents = {
"id": 1,
"name": "Test",
subsections: [
{
id: 2,
name: "Test1.1",
link: "test11.xml",
test: 34
},
{
id: 3,
name: "Test1.2",
link: "test12.xml",
test: 95
}
]
}
}]);
cxpControllers.directive('tree', function($compile) {
return {
restrict: 'E',
scope: {key: "=", content: "="},
templateUrl: "tree_renderer.html",
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone, scope) {
iElement.append(clone);
});
};
}
};
});
And then this is my template:
<script type="text/ng-template" id="tree_renderer.html">
{{key}}:
<ul ng-if="typeOf(content) == 'object' && content != null">
<li ng-repeat="(key, content) in content">
<tree key="key" content="content"></tree>
</li>
</ul>
<span ng-if="typeOf(content) != 'object'">
"{{content}}"
</span>
</script>
<ul>
<li ng-repeat="(key, content) in contents">
<tree key="key" content="content"></tree>
</li>
</ul>
This would work, except for one problem. Angular is turning the value of "content" into a string, preventing the recursion from working because it can't iterate over a string.
I have seen other questions like this, for example here, but their problem is that they used "#" in the directive scope, which converts to a string. But since I'm using "=", it should maintain the type.
Here's the output I'm seeing with the test data shown in the code above:
I would appreciate any help you can give. If you need more information I'll be happy to supply it.
The problem is with the typeOf function in your template. The compiled template doesn't find this function so it is never equal to 'object'. Add a controller to your directive to define it.
I took the plunkr and added this:
controller: function($scope) {
$scope.typeOf = function(val) {
return typeof val;
};
},
It does recognize it as an object. Check out the updated plunkr here.
Related
I am trying to create a few different directives that will work as search / filter tools for different parts of my application.
For this purpose i have created the following directive code:
app.directive("lbFilterDivision", ['divisionService', function (divisionService) {
return {
restrict: "E",
templateUrl: 'tpl/directives/lb-filters/lbFilterDivision.html',
scope: {
model: '='
},
link: function (scope, element, attr) {
scope.divisions = [];
divisionService.getList().then(function (result) {
scope.divisions = result;
})
}
};
}]);
The template attached to this is:
<select class="form-control"
ng-model="model"
ng-options="item.id as item.name for item in divisions"
fix-select-null="">
<option value="" translate="FORMS.DIVISION_PLACEHOLDER"></option>
Okay first of all let me explain the main idea.
The idea is that you have a search variable that will be passed to the directive. Then the two way binding should notify up through the system.
So say for instance i have the following HTML:
<lb-filter-division model="search.division.id"></lb-filter-division>
<li ng-repeat="user in users | filter:search"> </li>
As you can see i set the model = to search.division.id which means every time i change selected variable it should update the search.division.id variable and filter the list.
Sadly this is not the case.
Can anyone see what ive done wrong?
Edit - I found the answer. Apprently there was a syntax error in my code. Im so sorry! i will leave this code here if someone gets the same idea as my self.
Here is a fiddle:
fiddle
Solved the problem.
If you wish to copy or are looking to solve the same issue i can refer to this fiddle i made:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.users = [
{id: 1, name: "div1", division:{id: 1, name: 'hello'}},
{id: 2, name: "div2", division:{id: 2, name: 'hello2'}},
{id: 3, name: "div3", division:{id: 3, name: 'hello3'}}
]
}
myApp.directive("lbFilterDivision", function () {
return {
restrict: "E",
scope: {
model: '='
},
template: '<select ng-model="model" ng-options="item.id as item.name for item in divisions"></select>',
link: function (scope, element, attr) {
scope.divisions = [{id: 1, name:'hello'},{id: 2, name:'hello2'},{id: 3, name:'hello2'}];
}
};
});
fiddle
Good luck!
I have a list and want it to filter by my custom filter. But the value to it I want to put from custom directive with it's own scope. How to do it?
Body:
<body ng-controller="test">
<tr ng-repeat="item in list | myfilter: HowToPuttHereValue? >
Here is my custom filter:
.filter('myfilter', function(){
return function(array, num){
return array.slice(num, num+1);
}
})
And here is my custom directive:
.directive('mydirective', function() {
return {
restrict: "E",
template:"<input ng-model='counter'><button ng-click='getIt(counter)'>PRESS</button>",
scope:{
item: '='
},
link: function(scope, element, attr){
scope.getIt = function(counter){
console.log(counter);
}
}
}
})
Please see the Example:
JsFiddle Example
P.S. I guess I've already found a solution using "scope.$parent" . But is there a possibility to pass the value straight to a "myfilter: here? "
Here it is.
<div ng-app="hello">
<div ng-controller="forExampleController">
<ul>
<li ng-repeat="num in list | myfilter: howToPutHereFromDirective ">{{num}} </li>
</ul>
<mydirective item="list.length" filter-value="howToPutHereFromDirective"></mydirective>
</div>
</div>
function forExampleController($scope){
$scope.list = [1,2,3,4,5,6,7,8,9];
$scope.howToPutHereFromDirective = 3;
}
angular.module('hello', [])
.filter('myfilter', function(){
return function(array, num){
return array.slice(num, num+1);
}
})
.directive('mydirective', function() {
return {
restrict: "E",
template:"<input ng-model='counter'><button ng-click='getIt()'>PRESS</button>",
scope:{
item: '=',
filterValue: '='
},
link: function(scope, element, attr){
scope.getIt = function(){
scope.filterValue = parseInt(scope.counter);
}
}
}
});
Doing scope.$parent within isolated scope isn't too good indeed, because the objective of isolated scope is exactly the opposite.
I'm not sure what purpose item="list.length" two-way binding has to serve, but it is a bad idea.
In one of my Angular.JS controllers, I have the following:
app.controller("MyController", ["$scope", function($scope){
$scope.messages = [
new Message(1),
new Message(2)
];
$scope.addMessage = function(x) { $scope.messages.push(new Message(x)); }
}]);
Then in my main HTML page, I have
<message message="message" ng-repeat="message in messages">
This is bound to a directive:
app.directive("message", function() {
return {
restrict: "E",
scope: {
message: "="
},
templateUrl: "js/Directives/message.html"
};
});
The template file is:
<li class="message">{{message.msg}} </li>
However, when I call addMessage on the controller, while it does add to $scope.messsages, it doesn't actually refresh the ng-repeat and display the new message. How can I do this?
I would suggest some structural changes in your directive.
First of all, why not refer the original array itself instead of referring value at each iteration ??
<message messages="messages">
Then you can actually move ng-repeat part in your directive template, [You must note that since you're using = in message: "=", = binds a local/directive scope property to a parent scope property. So with =, you use the parent model/scope property name as the value of the DOM attribute. ].
Hence your directive will look like :
app.directive("message", function() {
return {
restrict: "E",
scope: {
messages: "="
},
templateUrl: "js/Directives/message.html"
};
});
and the subsequent template will look something like this :
<ul>
<li ng-repeat="message in messages" class="message">{{message.msg}} </li>
</ul>
You can find a demo plunker here
I have a question, code like this:
HTML:
<div class="overflow-hidden ag-center" world-data info="target"></div>
js:
.directive('worldData', ['$interval', function($interval) {
return {
scope: {
chart: '=info'
},
template: '<div>{{chart.aaa}}</div>',
link: function($scope, element, attrs) {
$scope.target = {'aaa': 'aaa'};
aaa = $scope.chart;
}
}
}])
The chart value is undefined, and template no value, but when I declare $scope.target within controller, the code works, why?
This should be generally the pattern:
.controller('myController', function($scope){
$scope.target = {'aaa': 'aaa'}; //In reality, you'd normally load this up via some other method, like $http.
})
.directive('worldData', [function() {
return {
scope: {
chart: '=info'
},
template: '<div>{{chart.aaa}}</div>'
}
}])
--
<div ng-controller="myController">
<div class="overflow-hidden ag-center" world-data info="target"></div>
</div>
Alternatively, the directive could be responsible for going and fetching the data, and not pass in anything to it. You'd only want to consider that if you don't need the data in multiple places.
I am new at angularjs and I want to create a directive to change text for human readable.
scope including records coming from database. I want to change them matching humanReadable array.
angular.module('app', [])
.directive("humanReadable", function () {
return {
restrict: "A",
replace: true
}
});
var humanReadable= [{
text: "first_name",
replace: "First Name"
},
{
text: "last_name",
replace: "Last Name"
}];
function MyCtrl($scope) {
$scope.comesFromDatabase = ["first_name", "last_name"];
}
my html is like this.
<div ng-app="app">
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in comesFromDatabase">{{item}} -
<span human-readable="item"></span>
</li>
</ul>
</div>
</div>
and jsfiddle is here
As Martinspire mentioned, it's better to use a filter which might look something like below -
angular.module('myapp')
.filter('humanReadable', [function () {
return function (str) {
return str.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; });
};
}]);
If you want directive only, with a bit of modification for the above code, it looks like this -
angular.module('myapp')
.directive('humanReadable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.html(attrs.humanReadable.split("_").join(" ").replace(/([^ ])([^ ]*)/gi,function(v,v1,v2){ return v1.toUpperCase()+v2; }));
}
};
});
Edit: I have done it without using your humamReadable array to generalize it assuming that you might find it useful instead of using a separate array.
angular.module('app', [])
.directive("humanReadable", function () {
return {
restrict: "A",
scope: {
items: '=',
humanReadable: '='
},
link: function (scope, element, attrs) {
scope.items.forEach(function (item, i) {
if (item.text === scope.humanReadable) {
element.text(item.replace);
}
});
}
}
});
Demo: http://jsfiddle.net/vhbg6104/4/
A better way would be to use a custom filter. You can read all about it in the docs https://docs.angularjs.org/guide/filter or api https://docs.angularjs.org/api/ng/filter/filter
You could take some inspiration from the translate-filters too: https://github.com/angular-translate/angular-translate
In summary, you would probably write it like so: {{item | human-readable}} or with ng-bind like so: <span ng-bind="item | human-readable">
Use the tools and i'm sure you can figure something out