When I remove app the code stops working - angularjs

I have the following code for angularjs working perfecly:
Working fine
But as soon as I use the above code without defining app I get an error and autocomplete stops working:
here is the code with jfiddle link:
function ctrl($scope) {
$scope.availableTags = [],
$scope.complete = function() {
/* return $scope.firstName + " " + $scope.lastName;*/
availableTags= [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$(document).ajaxComplete(function(){
$("#txt").autocomplete({
source: $scope.availableTags,
});
});
//return $scope.availableTags;
}
}
Here is jfiddle link:
jfiddle
Can anyone tell me the reason?

The app declaration is what tells Angular what code to load. It matches the ng-app directive in your html. Without that match, angular can't know what code you're trying to run.

Related

how can we get exact key match of object array in angularjs

I am trying to get the exact key match of object array in angularjs instead of that I am getting all matching results. How can i achieve that?
here is the controller code:-
var myApp = angular.module('myApp', []);
myApp.controller('ToddlerCtrl', function ($scope,$filter) {
$scope.toddlers = [
{
"name": "Toddler One",
"tid": "85",
},
{
"name": "Toddler Two",
"tid": "485",
},
{
"name": "Toddler Three",
"tid": "4485",
} ,
{
"name": "Toddler Four",
"tid": "8845",
}
];
var found = $filter('filter')($scope.toddlers, 85 );
console.log(found); // I want the exact match i.e. ("Toddler one" with "85" only) but I am getting 3 results.
});
here is the Plnkr
The solution is quite easy: Add a true as a third param to indicate that the search needs be exact. Note that 85 won´t match anything though, you need to put '85':
var found = $filter('filter')($scope.toddlers, '85' , true);
For more info check the comparator parameter in docs: Angular Filter

Error: ng:areq - controllers in different files

I'm trying to separate every controller in my angular app, but I have this error:
23:51:38.389 "Error: [ng:areq] http://errors.angularjs.org/1.5.0-rc.0/ng/areq?p0=skillsController&p1=not%20a%20function%2C%20got%20undefined
P/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:6:421
sb#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:22:41
Ta#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:22:128
af/this.$get</<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:84:42
B#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:62:118
v#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:63:115
Vf/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:72:397
e/<#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:123:217
pf/this.$get</m.prototype.$eval#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:137:442
pf/this.$get</m.prototype.$digest#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:135:33
pf/this.$get</m.prototype.$apply#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:138:234
g#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:91:372
t#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:95:492
ag/</v.onload#file:///C:/Users/Piotr/Desktop/ver%202/js/angular.min.js:97:31
"1 angular.min.js:111:399
e/<() angular.min.js:111
cf/this.$get</<() angular.min.js:84
e/<() angular.min.js:123
pf/this.$get</m.prototype.$eval() angular.min.js:137
pf/this.$get</m.prototype.$digest() angular.min.js:135
pf/this.$get</m.prototype.$apply() angular.min.js:138
g() angular.min.js:91
t() angular.min.js:95
ag/</v.onload() angular.min.js:97
pkApp.js:
angular.module('pkApp', ['Controllers']).value("version", "1.160110");
controllersModule.js:
angular.module('Controllers', []);
skillsController.js:
angular.module('Controllers', [])
.controller('skillsController', ['$scope', function($scope){
$scope.skills = [
"html",
"css",
"js",
"jquery",
"angularjs",
"php",
"mysql",
"joomla"
];
}]);
portfolioController.js:
angular.module('Controllers', [])
.controller('portfolioController', ['$scope', function($scope) {
$scope.sites = [{
name: "Site1",
href: "http://www.site1.pl",
img: "1"
}, {
name: "Site 2",
href: "http://www.site2.pl",
img: "2"
}, {
name: "Site 3",
href: "http://www.site3.pl",
img: "3"
}];
}]);
It looks like angular see new module and only first controller that was to it, next is treat as function?
Thank you in advance.
A simple Solution could be:
Define a variable with your module in pkApp.js
var app = angular.module('pkApp', []);
You can delete the controllersModule.js
Create your Controllers as follows:
app.controller('skillsController', ['$scope', function($scope){
$scope.skills = [
"html",
"css",
"js",
"jquery",
"angularjs",
"php",
"mysql",
"joomla"
];
}]);
Same thing with your portfolio controller. It doesn't matter how many files you like to use for your controllers.
See also: https://docs.angularjs.org/guide/controller
Hope, that helps...

tags-input show a a element of an array

hi i have a JSON like this:
pages[
{
"id": "74682309",
"labels": [
{
"term": "test1",
"probability": 0.069
},
{
"term": "test2",
"probability": 0.037
}
]
}];
and using tags-input i want the tags to read only the term and show the term so i can show and update.
i have
<tags-input ng-model="se.labels"></tags-input>
the 'se' comes from ng-repeat="se in searchCtrl.pages
Based on the documentation (http://mbenford.github.io/ngTagsInput/documentation/api) you can change the keyProperty and displayProperty to make it use "term" instead of "text"
I've created a fiddle to demonstrate how you can obtain the data needed, considering that the provided JSON is a valid JSON. Your JSON is invalid.
var myApp = angular.module('myApp',['ngTagsInput']);
myApp.factory('data', function() {
var data = [
{
"id": "74682309",
"labels": [
{
"text": "test1",
"probability": 0.069
},
{
"text": "test2",
"probability": 0.037
}
]
}];
return data;
});
myApp.controller('MyCtrl', ['$scope', 'data', function($scope, data) {
var values = [];
data.map(function(elem) {
return elem.labels.forEach(function(el) {
values.push({
"text" : el.text
});
});
});
$scope.tags = values;
}]);
And the html part:
<div ng-controller="MyCtrl">
<div class="elem">
<tags-input ng-model="tags"></tags-input>
</div>
</div>
Here is the fiddle:
http://jsfiddle.net/HB7LU/16554/
Update:
You haven't included the angular ng-tags-input extension as a tag into your question. Please see my updated fiddle:
http://jsfiddle.net/HB7LU/16557/

Angular JS $scope $resource & Directive - Directive Loading faster than scope thus cant see data

I am using an API to load (Data) to my $scope resource, and I took an example from a directive online to create a treeview. Recursive Tree View Example
However I am changing a few things to load data from an API. Please note the commented data... when I uncomment my data everything works great, however when I use $scope.treeFamily = TreeView.query() I think there is a delay between the directive executing and me getting no data. Any insight will be helpful. Thank you!
var module = angular.module("module", ["ngResource", "ngRoute"]);
module.factory('TreeView', function ($resource) {
return $resource('/api/TreeView/:Id', {}, {
//show: { method: 'GET', isArray: true }, //<--- need to do query instead of show....
query: { method: 'GET', isArray: false},
update: { method: 'PUT', params: { id: '#id' } },
delete: { method: 'DELETE', params: { id: '#id' } }
})
});
module.controller('TreeCtrl', function ($scope, TreeView) {
$scope.treeFamily = TreeView.query();
//$scope.treeFamily = {
// name: "Parent",
// children: [{
// name: "Child1",
// children: [{
// name: "Grandchild1",
// children: []
// }, {
// name: "Grandchild2",
// children: []
// }, {
// name: "Grandchild3",
// children: []
// }]
// }, {
// name: "Child2",
// children: []
// }]
//};
});
module.factory('RecursionHelper', ['$compile', function ($compile) {
var RecursionHelper = {
compile: function (element) {
var contents = element.contents().remove();
var compiledContents;
return function (scope, element) {
if (!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function (clone) {
element.append(clone);
});
};
}
};
return RecursionHelper;
}]);
module.directive("tree", function (RecursionHelper) {
return {
restrict: "E",
scope: { family: '=' },
template:
'<p>{{ family.name }}</p>' +
'<ul>' +
'<li ng-repeat="child in family.children">' +
'<tree family="child"></tree>' +
'</li>' +
'</ul>',
compile: function (element) {
return RecursionHelper.compile(element);
}
};
});
The Result from what i get there using the following HTML.
<!DOCTYPE html>
<html lang="en" ng-app="module">
<head>
<title></title>
</head>
<body>
<div class="container">
<div ng-controller="TreeCtrl">
<table>
<tr>
<th>Name</th>
</tr>
<tr ng-repeat="result in treeFamily">
<td> From Table: {{result.name}}</td>
</tr>
</table>
<tree family="treeFamily"></tree>
</div>
<div ng-view=""></div>
</div>
Result :
Name
From Table: Parent
HOWEVER, this is from the the ng-repeat within my table, so i know the API is sending DATA and it is readable.
{
ID: "1",
type: "Folder",
name: "Parent",
children: []
}
The problem is that it seems that the directive is not loading this data.... If however uncomment the built in data I have for that scope it works fine...
I have a feeling that my directive is loading faster than my API call so I get no data. Am i doing something wrong?
Any help will be appreciated!
Additional Research...
$scope.treeFamily = { "ID": "1", "type": "Folder", "name": "Harvest", "children": null };
$scope.treeFamily = [{ "ID": "1", "type": "Folder", "name": "Harvest", "children": null }];
This is the difference.....
If i try to do ng-repeat on
$scope.treeFamily = { "ID": "1", "type": "Folder", "name": "Harvest", "children": null };
It will not work because it is expecting an object [...]
$scope.treeFamily = [{ "ID": "1", "type": "Folder", "name": "Harvest", "children": null }];
Thus the above will work.
However, when using the recursive tree, it seems as though it does not EXPECT to see an object other than children... thus
$scope.treeFamily = [{ "ID": "1", "type": "Folder", "name": "Harvest", "children": null }];
will fail......
HOWEVER, I changed my API to return like this:
{ "ID": "1", "type": "Folder", "name": "Harvest", "children": null }
It still wont work!!!!!
This is probably an Angular version issue. Automatic promise unwrapping was removed in version 1.2. Change the code to:
var treeFamily = TreeView.query(function(){
$scope.treeFamily = treeFamily;
});
or use the more explicit promise syntax:
TreeView.query().$promise.then(function(treeFamily){
$scope.treeFamily = treeFamily;
});
I don't think the order matters. Since in the documentation of $resource it says:
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.
Are you sure data is returned from the server?

Why is my $watch showing an array that appears to be empty?

I'm working on creating an AngularJS directive in order to use D3 to render a visualization, but I'm running into problems when it comes to setting a $watch. The majority of my stuff looks extremely similar to the AngularJS tutorial. My resources are configured in a file called resources.json, which I'm sure is returning correctly.
Here's the relevant code of what I have so far:
app.js
var resourceApp = angular.module("resourceApp", [
'ngRoute',
'resourceControllers',
'resourceDirectives',
'resourceServices'
]);
/* ... routing config ... */
controllers.js
var resourceControllers = angular.module('resourceControllers', []);
resourceControllers.controller("OverviewCtrl", [ '$scope', 'Resource',
function($scope, Resource) {
$scope.resources = Resource.query();
}
]);
/* ... other controllers ... */
directives.js
var resourceDirectives = angular.module('resourceDirectives', []);
resourceDirectives.directive("resourceVisualization", function() {
return {
restrict: 'E',
scope: {
resources: '='
},
link: function(scope, el, attrs) {
// svg setup is here
scope.$watch("resources", function(nRes, oRes) {
if (nRes) {
// this logs an array of Resource objects
//(once expanded in Firebug)
console.log(nRes);
var cats = nRes.map(function(r) { return r.category; });
// this logs an empty array
console.log(cats);
}
});
}
};
});
overview.html
<ul>
<li ng-repeat="resource in resources">
{{resource.name}}
</li>
</ul>
<resource-visualization resources="resources"></resource-visualization>
resources.json (which is what services.js is configured to pull from)
[
{
"id": 1,
"category": "test",
"type": "sample",
"name": "Test1"
},
{
"id": 2,
"category": "test",
"type": "sample4",
"name": "Test2"
},
{
"id": 3,
"category": "fake",
"type": "sample1",
"name": "Test3"
},
{
"id": 4,
"category": "new",
"type": "sample2",
"name": "Test4"
}]
Now, I know that the REST call is working, because the <ul> is populated. However, in the directive, the logging statements are returning empty arrays. I'm aware of the the async-ness of $resource, but the object that is logged first in the $watch contains $resolved: true.
Am I missing something?
It's all fine. Your call to Resource.query() returns immediately an empty array. If the ajax call returns the real data, your array will be filled with the arrived data. So the first assignment to $scope.resources fires your $watch function with an empty array. You my solve your problem if you are using the $watchCollection function. See http://docs.angularjs.org/api/ng.$rootScope.Scope for further information.

Resources