Naming ng-app breaks data-binding in angularjs - javascript

I am working on my first website with AngularJS. My app works fine when I declare ng-app in the html tag. However, data binding stops working when I try to assign a name to the ng-app directive so that I can create a module with controllers and filters.
Here is my working code:
<!doctype html>
<html data-ng-app>
<head>
<meta charset="utf-8">
<title>Twittiment</title>
<link href="search_client.css" type="text/css" rel="stylesheet" />
<link href="tweet.css" type="text/css" rel="stylesheet" />
<script src="jquery.min.js"></script>
<script src="search_client.js"></script>
<script src="/js/highcharts.js"></script>
</head>
<body data-ng-controller="TweetCtrl">
<div id="main">
<div id="search_box">
<h1 id="title">Twitter Sentiment Analysis</h1>
<input name="search_terms" autofocus="autofocus" data-ng-model="query" />
<button id="search_button" data-ng-click="search()">Search</button>
<div id="data"></div>I can add:{{1+3}}</div>
<div id="search_results">Search tweets:
<input name="filter" data-ng-model="text" /><span>Displaying {{(tweets|filter:text).length}} of {{tweets.length}} tweets</span>
<div class="tweet" data-ng-repeat="tweet in tweets | filter:text">
<div class="tweet_left">
<div class="tweet_image"> <a href="https://twitter.com/{{tweet.user.screen_name}}">
<img src="{{tweet.user.profile_image_url}}">
</a>
</div>
</div>
<div class="tweet_right">
<div class="tweet_triangle"></div>
<div class="tweet_row">
<div class="tweet_username"> {{tweet.user.screen_name}}
<span class="tweet_name">{{tweet.user.name}}</span>
<span class="delete_tweet">Mark as irrelevant</span>
<input class="close_button" type="image" src="/xmark.jpg" alt="submit" ng-click="delete($index)">
</div>
</div>
<div class="tweet_row">
<div class="tweet_text">{{tweet.text}}</div>
</div>
<div class="tweet_row">
<div class="tweet_timestamp">
<img class="stream_bluebird" src="bird_16_blue.png"> <span class="retweets">{{tweet.retweet_count}} retweets</span>
{{tweet.created_at}}
<img src="reply.png" class="imageof_reply"> Reply
<img src="retweet.png" class="imageof_retweet"> Retweet
<img src="favorite.png" class="imageof_favorite"> Favorite
</div>
</div>
</div>
<div class="sentiment" data-ng-controller="RatingCtrl">
<div class="rating" data-ng-model="tweet.polarity">{{tweet.polarity}}</div>
<button data-ng-click="changeRating('Positive')">
<img class="positive" src="/thumbs-up-button.jpg">
</button>
<button data-ng-click="changeRating('Neutral')">
<img class="neutral" src="/thumbs-sideways-button.jpg">
</button>
<button data-ng-click="changeRating('Negative')">
<img class="negative" src="/thumbs-down-button.jpg">
</button>
</div>
</div>
</div>
</div>
<div class="total">
<h2 id="totalTitle"></h2>
<div>{{tweets.length}}</div>
<div id="totalPos"></div>
<div id="totalNeut"></div>
<div id="totalNeg"></div>
</div>
<div id="container" style="width:40%; height:400px;"></div>
<script src="/ang-Twittiment/app/lib/angular/angular.js"></script>
</body>
</html>
JS:
function TweetCtrl($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
$scope.tweets.splice(idx, 1);
};
}
function RatingCtrl($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
}
And here is the code that doesn't work:
<html data-ng-app="myApp">
JS:
var myAppModule = angular.module('myApp', []);
myAppModule.controller('TweetCtrl', function ($scope, $http) {
$scope.search = function () {
$http({
method: 'GET',
url: 'http://localhost:8080/search_server.php?q=' + $scope.query
}).success(function (data) {
$scope.tweets = data;
})
.error(function (data) {
alert("search error")
});
};
$scope.delete = function (idx) {
var person_to_delete = $scope.tweets[idx];
$scope.tweets.splice(idx, 1);
};
});
myAppModule.controller('RatingCtrl', function ($scope) {
$scope.changeRating = function (rating) {
$scope.tweet.polarity = rating;
}
});
Can anyone tell me why data binding stops whenever I assign a name to the ng-app directive? Is there a step I'm missing when configuring the module? Any help would be greatly appreciated, please let me know if more information is needed.

actually you need to put your angular.js file reference before angular.module statement so it can identify angular otherwise when you will check the javascript error it shows angular is not define

var myAppModule = angular.module('myAppModule', []);
This should do it.
When you declare ng-app="myApp", angular compiler searches for controllers registered with "myApp", but the controllers are registered with "myAppModule"

Related

UI-views: loading the url but not the content

Here's my code:
controller.js
angular.module('myApp',['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
// route to show all the polls
.state('polls', {
url: '/polls',
templateUrl: 'views/polls.html',
controller: 'pollsController'
})
// show new polls
.state('new', {
url: '/polls/add',
templateUrl: 'views/newPoll.html',
controller: 'newController'
});
$urlRouterProvider.otherwise('/polls');
})
.controller('pollsController', function($scope,$http) {
$http.get('/polls').then(function(data, status, headers, config) {
$scope.result = data;
}).catch(function(data) {
$scope.result = data;
});
})
.controller('newController',function($scope,$http) {
$http.get('/polls/add').then(function(data,status,headers,config) {
$scope.result = data;
}).catch(function(data) {
$scope.result = data;
});
});
index.html
<!DOCTYPE>
<html>
<head>
<meta charset="utf-8">
<!-- <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/darkly/bootstrap.min.css"> -->
<link rel="stylesheet" type="text/css" href="views/css/style.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
<script type="text/javascript" src="controller.js"></script>
</head>
<body ng-app="myApp">
<div id="topheader">
<h1>myApp</h1>
</div>
<div class="topnav" id="topnavigation">
<a ui-sref-active="active" ui-sref="new">Add poll</a>
<a ui-sref-active="active" ui-sref="polls">All polls</a>
</div>
<div class="container">
<div ui-view></div>
</div>
</body>
</html>
polls.html
<div class="content">
<h2>View your polls!</h2>
<div class="allPolls" ng-repeat="item in result.data.polls">
<li> {{item.title}}
</li>
</div>
</div>
newPoll.html
<div class="content">
<form>
Title: <br><input type="text" name="title"><br>
Options (add line break between options): <br>
<textarea type="text" name="options">
</textarea>
<br>
<button type="button">Create new poll</button>
</form>
</div>
So now when I press the "Add poll"-button from the polls-page the page loads a page where is only the topnavigation-bar. When I press the "Add poll"-button again, the page loads the form from newPoll.html.
The url changes on the first click so everything should be working on the first click?

AngularJS $location directory

Main page URL: http://localhost:3000/
Current second page URL: http://localhost:3000/#/titleDetails.html
Expected second page URL: http://localhost:3000/titleDetails.html
Currently when I click on the title in my main page, the URL contains an extra /# which causes the page to be redirected to titleDetails.html.
The directory of titleDetails.html and index.html is in the same directory.
May I know how can I fix this?
Original Post: AngularJS Display 1 Post in New Page
app.js
(function () {
angular
.module("BlogApp", [])
.config(function($locationProvider) {
$locationProvider.html5Mode(true).hashPrefix('!');
})
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('/titleDetails.html');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Console Error in index.html:
angular.js:13708 Error: [$location:nobase] http://errors.angularjs.org/1.5.7/$location/nobase
at angular.js:38
at sf.$get (angular.js:13384)
at Object.invoke (angular.js:4709)
at angular.js:4508
at d (angular.js:4655)
at e (angular.js:4679)
at Object.invoke (angular.js:4701)
at R.instance (angular.js:10234)
at m (angular.js:9147)
at g (angular.js:8510)
Angular has 3 routing operates:
Hashbang Mode
HTML5 Mode
Hashbang in HTML5 Mode
You can configure: $locationProvider.html5Mode(true).hashPrefix('!');
Check documentation

AngularJS Display 1 Post in New Page

I want to display only Test Post 1 in next html page titleDetails.html when user clicks Test Post 1 in index.html
1) titleDetails() in index.html:
<a ng-click="titleDetails(post)">{{ post.title }} </a>
2) controller variables and titleDetails() method:
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('#/titleDetails');
}
3) body in titleDetails.html:
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
FULL CODE:
app.js
(function () {
angular
.module("BlogApp", [])
.controller("BlogController", BlogController);
function BlogController($scope, $http, $rootScope, $location) {
$scope.createPost = createPost;
$scope.deletePost = deletePost;
$scope.editPost = editPost;
$scope.updatePost = updatePost;
$scope.titleDetails = titleDetails;
$scope.postDetail = null;
function init() {
getAllPosts();
}
init();
function titleDetails(post)
{
$scope.postDetail = post;
$location.path('#/titleDetails');
}
function updatePost(post){
console.log(post);
$http
.put("/api/blogpost/"+post._id, post)
.success(getAllPosts);
}
function editPost(postId){
$http
.get("/api/blogpost/"+postId)
.success(function(post){
$scope.post = post;
});
}
function deletePost(postId){
$http
.delete("/api/blogpost/"+postId)
.success(getAllPosts);
}
function getAllPosts(){
$http
.get("/api/blogpost")
.success(function(posts) {
$scope.posts = posts;
});
}
function createPost(post) {
console.log(post);
$http
.post("/api/blogpost",post)
.success(getAllPosts);
}
}
})();
index.html
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<input ng-model="post.title" class="form-control" placeholder="title"/>
<textarea ng-model="post.body" class="form-control" placeholder="body"></textarea>
<button ng-click="createPost(post)" class="btn btn-primary btn-block">Post</button>
<button ng-click="updatePost(post)" class="btn btn-success btn-block">Update</button>
<div ng-repeat="post in posts">
<h2>
<a ng-click="titleDetails(post)">{{ post.title }} </a>
<a ng-click="editPost(post._id)" class="pull-right"><span class="glyphicon glyphicon-pencil"></span></a>
<a ng-click="deletePost(post._id)" class="pull-right"><span class = "glyphicon glyphicon-remove"></span></a>
</h2>
<em>{{post.posted}}</em>
<p>{{post.body}}</p>
</div>
</div>
</body>
</html>
titleDetails.html:
<!DOCTYPE html>
<html lang="en" ng-app="BlogApp">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="app.js"></script>
<title>Title</title>
</head>
<body>
<div class="container" ng-controller="BlogController">
<h1>Blog</h1>
<div>
<h2>
<a>{{ postDetail.title }} </a>
</h2>
<em>{{postDetail.posted}}</em>
<p>{{postDetail.body}}</p>
</div>
</div>
</body>
</html>
Hope this following steps work for you
Pass post object to titleDetail() function.
In index.html
<a ng-click="titleDetails(post)">{{ post.title }} </a>
In function assign post to $rootScope variable
$scope.titleDetails = function(post) {
$rootScope.postDetail = post;
}
Now your titleDetail.html page controller:
$scope.post = $rootScope.postDetail;
a new scope variable in BlogController
$scope.postDetail = null;
and method titleDetails() be like
$scope.titleDetails = function(post) {
$scope.postDetail = post;
}
and also make change in index.html
<a ng-click="titleDetails(post)">{{ post.title }} </a>

Controller data not passed to directive

I started looking into angular and cannot seem to figure out why my data is not passed to my directive. I have code here: https://plnkr.co/edit/ONwYevQ4NbvBVjTwARHl?p=preview
My Code:
app.js:
var app = angular.module('mjApp', []);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.name = "m.jacionis";
$scope.avatar = null;
$scope.fetchData = function(){
var callUrl = 'https://api.github.com/search/users?q=' + $scope.name;
$scope.avatar = "http://images.clipartpanda.com/sad-face-clipart-black-and-white-9c4eqRyyi.png";
$http({
method: 'GET',
url: callUrl
}).then(function successCallback(response) {
$scope.avatar = response.data.items.length > 0 ?
response.data.items[0].avatar_url : $scope.avatar;
console.log($scope.avatar);
}, function errorCallback(response) {
console.log('avatar stays the same');
});
};
}]);
app.directive("mjDirective", function(){
return {
restrict: "EA",
templateUrl: 'template.html',
scope: {
name: "=name",
avatar: "=avatar"
}
};
});
index.html:
<!DOCTYPE html>
<html ng-app="mjApp">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name userAvatar=userAvatar></mj-directive>
</div>
</body>
</html>
template.html:
<div class='line'>
<p>Name : <strong>{{name}}</strong></p>
<img class="avatar" src={{avatar}}/>
</div>
name value is passed, but avatar value which I get when I fetch data isn't. I cannot seem to figure out, why it is like that. Any ideas or suggestions would help a lot.
I think you have taken wrong name userAvatar instead of avatar since you binded avatar
your bindings,
scope: {
name: "=name",
avatar: "=avatar"
}
So, you have to take name and avatar in directive.
<body>
<div class="parent" ng-controller="MainController">
<div class="line">
<input type='text' ng-model='name' />
<input type="button" ng-click="fetchData()" value="Submit User Name" />
</div>
<mj-directive name=name avatar=avatar></mj-directive>
</div>
</body>
change directive,
<mj-directive name=name avatar=avatar></mj-directive>
I think you need to wrap the name and avatar in strings when you use them in HTML.
<mj-directive name="name" userAvatar="userAvatar"></mj-directive>
Also inside the directive you should have:
scope: {
user: "=name"
avatar: "=userAvatar"
}

TypeError: undefined is not a function when triggering AJAX requests in ASP.NET

I followed tutorial on this LINK to create AJAX requests on my angularJS appliction (CRUD operations). After I finished coding I tried to perform AJAX request (get all data from database) but when I lunch my application I got this error:
TypeError: undefined is not a function
at new <anonymous> (http://localhost:49510/Scripts/application/controllers.js:4:15)
Does someone knows where's the problem and how to fix it?
Here is code:
controller:
app.controller('ContactsController', [
'$scope', '$http', '$location', 'contactsService',
function ($scope, $location, $http, contactsService) {
$http.get('/contacts/').success(function (data) { //triggers error
alert(data);
$scope.contact = data;
$scope.loading = false;
})
.error(function () {
alert ("An Error has occured while loading contacts!");
// $scope.loading = false;
});
$scope.editContact = function (id) {
$location.path('/edit-contact/' + id);
};
$scope.displayContact = function (id) {
$location.path('/display-contact/' + id);
};
$scope.showDetails = function (id) {
var el = angular.element(document.getElementById('#ct-details-' + id));
el.toggleClass('details-hidden');
}
}
]);
and here is contacts.html template:
<div class="container view">
<header>
<h3>Contacts</h3>
</header>
<div>
<a class="nav-pills hover" href="#/add-contact">Add Contact</a>
</div>
<br /><br />
<div class="row">
<ul class="span5" >
<li class="nav-pills nav-stacked contact-row" data-ng-repeat="contact in contacts | orderBy:'firstName'">
<span id="ct-details-{{contact.id}}" data-ng-click="displayContact(contact.id)" style="cursor:pointer;" class="contact-data details-hidden" href="" >
<span class="span3 contact-name" >{{contact.firstName + ' ' + contact.lastName}}
{{contact.emailAddress}}</span>
</span>
<button class="btn editContact" data-ng-click="deleteContact(contact.id)">Delete</button>
<button class="btn editContact" data-ng-click="editContact(contact.id)">Edit</button>
</li>
</ul>
</div>
</div>
and here is index.cshtml file:
<!DOCTYPE html>
<html ng-app="contactsManager">
<head>
<title>Contacts</title>
</head>
<body>
<div class="navbar navbar-top">
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/custom.css" rel="stylesheet" />
<div class="navbar-inner">
<div class="container">
<h2>Contacts</h2>
</div>
</div>
</div>
<div ng-view class="example-animate-container"
ng-animate="{enter: 'example-enter', leave: 'example-leave'}"></div>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/application/application.js"></script>
<script src="~/Scripts/application/controllers.js"></script>
<script src="~/Scripts/application/contactsService.js"></script>
</body>
</html>
The order of arguments in the controller function has to match the order in the parameter array.
You have mixed the order of $http and $location.
So change your function signature to
app.controller('ContactsController', [
'$scope', '$http', '$location', 'contactsService',
function ($scope, $http, $location, contactsService) {

Categories

Resources