Editing JSON search results from within Angular - javascript

I am now pulling data from a external JSON URL properly to the master page, but my detail page doesn't seem to pass on the object initallt received from http.get. This master part of the app can be viewed in a Code Pen at CODEPEN
<label class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="search" ng-model="query" placeholder="Search Slugname">
<button class="button button-dark" ng-click="getOrders()">Submit</button>
</label>
If my user wanted to change the date(order.date)value manually to say "10/8/16". How can I access/edit any of the JSON values that are returned from the external API?
I eventually wish to edit the returned JSON data within my app and then post that revised data back to a PHP API server.

Your main issue is that you want to modify the incoming data from the $http call.
You can implement an http interceptor, the method response will take the response modify it and then return it to the caller. Since the http interceptor will take all the incoming requests just check the url start to not modify other requests.
angular.module('ionicApp', ['ionic'])
.factory('httpInterceptor', function($q, $rootScope) {
var httpInterceptor = {
response: function(response) {
var deferred = $q.defer();
var results = response.data;
var urlStart = 'http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=';
if (response.config.url.startsWith(urlStart)) {
angular.forEach(results, function(result, key) {
result.date = '10/8/16';
});
}
deferred.resolve(response);
return deferred.promise;
}
};
return httpInterceptor;
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
})
.controller('ListController',
['$scope', '$http', '$state', '$stateParams', '$window', '$location',
function($scope, $http, $state, $stateParams, $window, $location) {
$scope.getOrders = function(query) {
$http.get('http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=' + query)
.success(function(data) {
$scope.orders = data;
})
}
$scope.orders = [];
}]);
The only modification that I've made on your html is to send query param directly to the function on the ng-click
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tabs Example</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="ListController">
<ion-header-bar class="bar-dark" align-title="center">
<h2 class="title">Order Search</h2>
</ion-header-bar>
<ion-content padding="true" class="has-header">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="query" placeholder="Search Slugname">
<button type="submit" class="button button-dark" ng-click="getOrders(query)">Submit</button>
</div>
<p>An example and working slug search term is test-3. The JSON can be viewable in a browser using https://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=test-3</p>
<ion-list>
<ion-item ng-repeat="order in orders | filter:query" class="item-thumbnail-left item-text-wrap" href="#/tab/list/{{order.id}}">
<h2>Page ID: {{order.id}}</h2>
<h3>Date created: {{order.date}}</h3>
<h2>Page URL: £{{order.link}}</h2>
<h2>Page Title: £{{order.title/rendered}}</h2>
</ion-item>
</ion-list>
</ion-content>
</body>
</html>
I almost forgot the codepen is here: http://codepen.io/pachon1992/pen/QEodJR
EDIT ---------------------------
As per comments you want your user to update manually the data right? as an example you would like to update the date, you can do enabling a input for the user to edit the data, since angular is two-way data-binding will modify your data.
<html ng-app="ionicApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Tabs Example</title>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
</head>
<body ng-controller="ListController">
<ion-header-bar class="bar-dark" align-title="center">
<h2 class="title">Order Search</h2>
</ion-header-bar>
<ion-content padding="true" class="has-header">
<div class="item item-input">
<i class="icon ion-search placeholder-icon"></i>
<input type="text" ng-model="query" placeholder="Search Slugname">
<button type="submit" class="button button-dark" ng-click="getOrders(query)">Submit</button>
</div>
<p>An example and working slug search term is test-3. The JSON can be viewable in a browser using https://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=test-3</p>
<ion-list>
<ion-item ng-repeat="order in orders | filter:query" class="item-thumbnail-left item-text-wrap" href="#/tab/list/{{order.id}}">
<h2>Page ID: {{order.id}}</h2>
<div><input type="text" ng-model="order.date"></div>
<h2>Page URL: £{{order.link}}</h2>
<h2>Page Title: £{{order.title/rendered}}</h2>
</ion-item>
<button type="button" class="button button-dark" ng-click="update()">Update</button>
</ion-list>
</ion-content>
</body>
</html>
In your controller you can call http service for every order calling via typically to a PUT endpoint
angular.module('ionicApp', ['ionic'])
.controller('ListController', ['$scope', '$http', '$state', '$stateParams', '$window', '$location',
function($scope, $http, $state, $stateParams, $window, $location) {
$scope.query = "";
$scope.getOrders = function(query) {
$http.get('http://mvcframe.com/wpapi/wp-json/wp/v2/pages?slug=' + query)
.success(function(data) {
$scope.orders = data;
});
}
$scope.orders = [];
$scope.update = function() {
angular.forEach($scope.orders, function(order) {
//whetever url you are using
$http.put('http://mvcframe.com/wpapi/wp-json/wp/v2/pages/update/' + order.id, order, {})
.success(function(data) {
console.log('updated');
});
});
};
}
]);
I've edited the codepen

https://codepen.io/anon/pen/qNLOAP
So apparently it seems you cannot have a button in a <label> with ng-click. I changed the label to a <div> and it started working.
The search doesn't work at the moment but that should get you going.

Please resolve listed points.
1> tabs.home state you don't have injected controller and the other thing is also define home.html and
2> all other template separably in templates folder parallel to your controllers.
3> http call to http://mvcframe.com/wpapi/wp-json/wp/v2/pages requires cross origin domain support for that you can use chrome (CORS) plugin.
it will work for me. Please check and let me know if it works.

Working Pen:
https://codepen.io/jasondecamp/pen/gryxGQ
The two changes I made were:
1) Added $parent to the reference to 'query' in the input field ng-model. I am not that familiar with ionic, but my guess is that ion-content directive adds a child scope so to reference query you need to look to the parent.
<input type="search" ng-model="$parent.query" placeholder="Search Slugname">
2) I changed the http get url to be https because I was getting insecure access warnings.
As a note, you should not need to use any JSON parsing function when the response is pure JSON data, because angular $http service will automatically recognize the data and convert it into a js object.

Related

ebay shopping API AngularJS unexpected error

angular.module('BeautyCare', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('tabs', {
url: "/tab",
abstract: true,
templateUrl: "templates/tabs.html"
})
.state('tabs.Store', {
url: "/Store",
views: {
'Store-tab': {
templateUrl: "templates/Store.html",
controller: 'StoreTabCtrl'
}
}
})
.state('tabs.SalonGalary', {
url: "/SalonGalary",
views: {
'SalonGalary-tab': {
templateUrl: "templates/SalonGalary.html",
controller :'SalonGalaryCtrl'
}
}
})
.state('tabs.Profile', {
url: "/Profile",
views: {
'Profile-tab': {
templateUrl: "templates/Profile.html"
}
}
})
.state('tabs.Alerts', {
url: "/Alerts",
views: {
'Alerts-tab': {
templateUrl: "templates/Alerts.html"
}
}
});
$urlRouterProvider.otherwise("/tab/Store");
});
.controller('StoreTabCtrl', function($scope,$http,$log) {
var items =null;
$log.debug('start debug');
var url="http://open.api.ebay.com/shopping?GLOBAL-ID=EBAY-IN&QueryKeywords=Iphone&ResponseEncodingType=JSON";
url+="&appid=API_ID&callback=JSON_CALLBACK._0";
url+="&callname=FindPopularItems&version=713?callback=JSON_CALLBACK";
$log.debug($http.jsonp(url)
.success(function(data) {
items=data;
console.log(items);
})
.error(function(data) {
//alert("ERROR");
}));
});
<html >
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Beauty Care</title>
<!-- MyBeauty , BeautyCare,BeautyEye,BeautyShop,BeautySalon !-->
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="js/app.js"></script>
<script src="js/Service.js"></script>
<script src="js/Controllers.js"></script>
<!-- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBLSOMXsw_sxOlRpyBj16g5iaewLHDpSes&libraries=places"></script>
-->
</head>
<body ng-app="BeautyCare">
<ion-nav-bar class="bar-positive">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
<script id="templates/tabs.html" type="text/ng-template">
<ion-tabs class="tabs-icon-top tabs-positive">
<ion-tab title="" icon="ion-ios-cart" href="#/tab/Store">
<ion-nav-view name="Store-tab"></ion-nav-view>
</ion-tab>
<ion-tab title="" icon="ion-navicon-round" href="#/tab/SalonGalary">
<ion-nav-view name="SalonGalary-tab"></ion-nav-view>
</ion-tab>
<ion-tab title="" icon="ion-android-person" ui-sref="tabs.Profile">
<ion-nav-view name="Profile-tab"></ion-nav-view>
</ion-tab>
<ion-tab title="" icon="ion-ios-bell" ui-sref="tabs.Alerts">
<ion-nav-view name="Alerts-tab"></ion-nav-view>
</ion-tab>
</ion-tabs>
</script>
<script id="templates/Store.html" type="text/ng-template">
<ion-view view-title="BeautyCare Store" cache-view="false">
<ion-content class="padding" >
<ion-list>
<ion-item class="item-icon-right" ng-repeat="item in items">
<h1>{{item.TimeStamp }}</h1>
<!--<p>{{ item.title}}</p> !-->
<i class="icon ion-chevron-left icon-accessory"></i>
<ion-option-button class="button-positive" ng-click="viewFriend(viewFriend(data.idfriends))">View Friend</ion-option-button>
<ion-option-button class="button-assertive" ng-click="deleteFriend(remove(data.idfriends))">Delete</ion-option-button>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
</script>
<script id="templates/SalonGalary.html" type="text/ng-template">
<ion-view view-title="BeautyCare Salon Galary" cache-view="false">
<ion-content class="padding">
</ion-content>
</ion-view>
</script>
<script id="templates/Profile.html" type="text/ng-template">
<ion-view title="My Profile" cache-view="false">
<ion-content>
</ion-content>
</ion-view>
</script>
<script id="templates/Alerts.html" type="text/ng-template">
<ion-view view-title="My Alerts" cache-view="false">
<ion-content class="padding">
</ion-content>
</ion-view>
</script>
</body>
</html>
</body>
</html>
I tried to use $http.get with no luck , the code showing unexpected error.
i appreciate any help to solve this issue or workaround to use $http.get . I tried different examples but still not getting issues solved. Thanks in advance
Let's take a closer look at the URL you are attempting to send to the eBay API:
http://open.api.ebay.com/shopping?GLOBAL-ID=EBAY-IN&QueryKeywords=Iphone&
ResponseEncodingType=JSON&appid=Mawsem77f-2832-4be9-93d8-e257a245be3&
callback=JSON_CALLBACK._0&callname=FindPopularItems&version=713?callback=JSON_CALLBACK
I counted three problems with this:
the version parameter has an invalid value: 713?callback=JSON_CALLBACK. This parameter appears to require a numeric value. Note that this part of the URL is already in the query string, so the ? here won't be interpreted as the start of the query string or as an argument separator.
If callback=JSON_CALLBACK at the end of the URL is supposed to be another URL parameter name and value, then you have specified the callback parameter with two different values. You only need to specify this parameter once, and you also need to make up your mind about which value to use.
As you are making a JSONP request you need to specify the name of a function to wrap the returned JSON in. However, according to the eBay API documentation, you are using the wrong parameter for the name of the callback function. If the parameter callback has the value true, the response will be wrapped in a call to a function named _cb_FindPopularItems. Other values for this parameter appear to be ignored. It seems you want to use the callbackname parameter instead. So, try removing both callback parameters from your URL and adding either callbackname=JSON_CALLBACK or callbackname=JSON_CALLBACK._0 (it's not clear which one you intend here).
This also explains the syntax error: responses to JSONP requests are assumed to be executable JavaScript but the response you are getting is actually some JSON data.
I have not tested this, but I would hope the following URL (wrapped for readability) would work. You may need to add the ._0 suffix to the callback name:
http://open.api.ebay.com/shopping?GLOBAL-ID=EBAY-IN&QueryKeywords=Iphone&
ResponseEncodingType=JSON&appid=Mawsem77f-2832-4be9-93d8-e257a245be3&
callbackname=JSON_CALLBACK&callname=FindPopularItems&version=713
Finally, please consider changing your eBay app ID. You've now posted it on the public internet and anyone who views this question can now use it. I've never used eBay nor its API before, so I'll leave it up to you to figure out how to do this.

ng-repeat not iterating through list of images in JSON

I'm quite new to Angular and am having trouble using the $http service to make a GET request for images in JSON (just a plain array of images). For every image, I want to repeat that and add them into my ng-src. I'm trying to achieve a layout similar to Instagram.
So I think the $http.get part is correct where I store it into $scope.imageUrls, and from there I iterate through it using ng-repeat. Then from there, for each iteration, I plug that into ng-src in my img tag and I just don't know how to debug from there.
HTML:
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>
JS:
var app = angular.module('instagram', []);
app.controller('PostController', ['$scope', '$http', function($scope, $http) {
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data;
console.log($scope.imageUrls);
});
}]);
I tried used console.log to check for errors, but the data seems to be there. Is it just returning the block of data rather than each element/image in the JSON?
Checking the console: console.log($scope.imageUrls)
I also tried using {{imageUrl.url}} as ng-src but that seemed to trigger errors as well. I set up a Plnkr:
http://plnkr.co/edit/yQpCIRp9FHdDHTMA1HCL?p=preview
This has been bugging me for awhile, so if you can help, thanks!
I update your plunker http://plnkr.co/edit/hNn1YdVh8w7l3dEgh3LU?p=preview:
In $http you get a responsa that contains more informations that only data. To get data you must do it :
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (response) {
$scope.imageUrls = response.data;
console.log($scope.imageUrls);
});
And in ng-repeat you must add track by argument because image can be duplicate
You are setting imageUrls to an object. It needs to be an array. If you look in the debugger your response is this:
You want whats in data.data (You also should define the imageUrls variable ($scope.imageUrls = []')
<!doctype html>
<html ng-app="instagram">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var app = angular.module('instagram', []);
app.controller('PostController', ['$scope', '$http', function($scope, $http) {
$scope.imageUrls = [];
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data.data;
});
}]);
</script>
</body>
</html>
updated plunkr http://plnkr.co/edit/agVrWD8I4581a0702ehy?p=preview
you have to get data.data
$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data.data;
});
and use track by $index in the ng-repeat because you have duplicate
<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls track by $index">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>
First of all in $http method the response value is an object containing "data" element that is the data you need so use this :
$scope.imageUrls = data.data;
then you have duplicate image url , in this case ng-repeat returns an error so use this instead :
<div class="post" ng-repeat="imageUrl in imageUrls track by $index">

How to request API data with $http service

I'm developing an app with Riot Games API but this example it's done with REST Countries API. https://restcountries.eu/rest/v1/alpha/co
I use a MEAN.IO stack and this is my code:
test.html
<html ng-app="lolData">
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.1.3/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.1.3/material.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<section id="center" ng-controller="summonerStats">
<form ng-submit="search()">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="text" id="summonerName" placeholder="Summoner Name">
<label class="mdl-textfield__label" for="sample1"></label>
</div>
<input class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit" value="Search"/>
<p ng-show="show">
{{ mystats.name }}
</p>
</form>
</section>
</body>
</html>
test.js
'use strict';
var lolData = angular.module('lolData', []);
console.log("before controller");
lolData.controller('summonerStats', function($scope, $http) {
var url = "https://restcountries.eu/rest/v1/alpha/co";
console.log("inside controller");
$scope.show = false;
$scope.search = function() {
$http.get(url)
.success(function(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
});
};
});
When I refresh the page the code is executed until "before controller" console.log. It can't get inside lolData.controller. And in the browser console displays the following error.
And html doesn't accept the embeded javascript scope.
What am I missing?
Update 1:
I added the index.html in a codepen: Index.html
And Header.html in a codepen too: header.html
Not sure if this is your problem, but $http.success (and $http.error) has been depreciated since v1.4.4. Instead, use callback functions for success and error
var url = "https://restcountries.eu/rest/v1/alpha/co";
$http.get(url).then(
function successCallback(response) {
$scope.mystats = response;
$scope.show = true;
console.log("inside success controller");
}, function errorCallback(error) {
console.log(error);
});
Your response object doesn't do what you think it does.
From angular's docs you see the response has multiple properties attached to the returned object.
You want
$scope.mystats = JSON.parse(response.data);

AngularJS View not updating when Controllers $scope variables changed?

basically my issue is that I have a AngularJS view (home.html) which contains a variable in double brackets like so: {{message}}
When the $scope.message variable is modified, the view with does not update, although it should? I have tried adding $scope.$apply() which results in an exception along the lines of 'Action in Progress'
Check my code below. The {{message}} part in home.html is not being updated when $scope.doLogin is called in MainCtrl, even though I have set $scope.message to a new value in that function.
Any help is greatly appreciated and if any further info is needed, please ask.
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link href="stylesheet.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.4/angular-route.min.js"></script>
<base href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.9/ngStorage.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="#">TriviaAttack</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<form id="loginForm" class="navbar-form navbar-right">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control" ng-model="loginData.username">
</div>
<div class="form-group">
<input type="text" placeholder="Password" class="form-control" ng-model="loginData.password">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" ng-click="doLogin()">Sign In</button>
</div>
</form>
</div>
</div>
</nav>
</div>
<div ng-view>
</div>
</div>
<script src="./app/app.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">
</body>
</html>
home.html
<div>
<h1>Welcome to the Home Page</h1>
<p>{{message}}</p>
</div>
app.js
var myApp = angular.module('myApp',['ngRoute', 'ngStorage']);
myApp.controller('MainCtrl', ['$rootScope', '$scope', '$location',
function($rootScope, $scope, $location) {
$scope.message = 'testing message';
$scope.loginData = {
username: '',
password: '',
loggedIn: false
}
$scope.doLogin = function() {
$scope.message = 'message changed!';
$scope.$apply();
Auth.doLogin($scope.loginData.username, $scope.loginData.password)
.success(function(data) {
if (data.success) {
AuthToken.setToken(data.token);
$location.path('/home');
console.log($scope.loginData.loggedIn);
}
});
$scope.loginData = {};
}
}]);
//Middleware for all requests which adds the users token to the HTTP header.
myApp.factory('TokenInterceptor', ['$q', '$location', '$localStorage',
function($q, $location, $localStorage) {
//On each request, check if the user is logged in with a valid token.
var interceptor = {
request: function(config) {
config.headers['X-Authorization-Token'] = $localStorage.token;
return config;
},
responseError: function(response) {
if(response.status === 401 || response.status === 403) {
$location.path('/login');
}
return $q.reject(response);
}
};
return interceptor;
}]);
myApp.config(['$routeProvider','$locationProvider','$httpProvider',
function($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.
when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'MainCtrl'
}).
when('/home', {
templateUrl: './app/views/home.html',
controller: 'MainCtrl'
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
$httpProvider.interceptors.push('TokenInterceptor');
}
]);
console.log('app.js loaded!');
Each time a view is loaded ,the controller code with new scope executes so the new message is not reflected.
So the flow be like
landingPage's controller which is MainCtrl with its scope when $scope.doLogin is executed will change the $scope.message variable to "Message Changed" and upon changing location to home , the MainCtrl is assigned to home page with new scope which would continue executing the very first line of MainCtrl i.e.
$scope.message = 'testing message';
As you have decided to use common controller for login and home pages
Try removing controller option in
when('/', {
templateUrl: './app/views/landingpage.html',
controller: 'MainCtrl'
}).
when('/home', {
templateUrl: './app/views/home.html',
controller: 'MainCtrl'
})
And assign controller in
<div ng-controller="MainCtrl">
<!--omitted-->
<div ng-view></div>
</div>
Or else other options would be to pass parameters or use
ui-router wherein nested views would automatically inherit from parent controllers without rerunning the controller logic.
Problem is in controller coverage
<div ng-controller="MainCtrl">
<!--omitted-->
</div>
<div ng-view></div>
Your $scope.message is tight to your MainCtrl, so when ng-view is populated, you except that it has MainCtrl, but indeed it's outside of that div, so just doesn't see that variable, to make it work, insert ng-view to MainCtrl div like shown below
<div ng-controller="MainCtrl">
<!--omitted-->
<div ng-view></div>
</div>
But here's the actual problem
You tend to use ng-route but you don't have any route configurations, ng-view will never be populated with home.html unless you configure you routeProvider, first of all, make some routes like described here, perform your form action, redirect to page and populate views accordingly, it should work.

AngularJS v1.3.13 ng-view not triggering controller to render template

Having an issue using the ng-view to render a template from my controller.
The index.html file is initially served to the client and looks like.
<!doctype html>
<html lang="en" ng-app="hlmApp">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title></title>
<link rel="stylesheet" href="#Model.Root.Resource/bower_components\\/bootstrap/dist/css/bootstrap.css">
#RenderSection("BootScript")
<!-- app.js will load the angular module -->
<script src="#Model.Root.Resource/bower_components/angular/angular.js"></script>
<script src="#Model.Root.Resource/bower_components/angular-route/angular-route.js"></script>
<script src="#Model.Root.Resource/app/app.js"></script>
<script src="#Model.Root.Resource/app/controllers/controllers.js"></script>
</head>
<body>
<div class="container">
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>A link here</li>
</ul>
</div>
</div>
<div ng-view></div>
#*<div ng-controller="tempController">{{Heading}}</div>*#
</div>
#RenderBody()
</body>
</html>
the server pushes down my app.js and controllers.js file along with the deps.
/// ap.js ///
var hlmApp = angular.module('hlmApp', ['ngRoute', 'MyTempControllers']);
hlmApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/Holdings', {
templateUrl: 'templates/temp.html',
controller: 'controllers/tempController'
});
}]);
the controller is pretty simple and is as follows
var MyTempControllers = angular.module('MyTempControllers', []);
MyTempControllers.controller('tempController', ['$scope', function () {
console.log("stuff happening");
$scope.Heading = "Hello World";
}]);
then the html template is as follows
<div>
<h3>{{Heading}}</h3>
</div>
When I use the ng-view nothing ever renders. the controller is never triggered in the debugger. If I specifically call out the controller via the ng-controller then everything shows up. can someone point out my error here?
You need these 3 changes:
1) add $scope as a parameter in your controller function
MyTempControllers.controller('tempController', ['$scope', function ($scope) {
...
}]);
2.
Change
controller: 'controllers/tempController'
to
controller: 'tempController'
FYI, the naming convention for a controller is to begin with a capital letter for Controller.
3. In addition, you should add a
.otherwise({
template: templates/temp.html,
controller: 'tempController'
});
so that when no route matches, it goes to default-page-name.html. This is what's happening in your case, when you first load the page, no route matches. If you want to see temp.html, you have to 1) either click on a link that goes to #/Holdings, or 2) use '/Holdings' as the "otherwise" route, as indicated above.
Try this:
hlmApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/Holdings', {
templateUrl: 'templates/temp.html',
controller: 'tempController' // just the name
});
}]);
and also $scope is missing in parameters:
MyTempControllers.controller('tempController', ['$scope', function ($scope) {
console.log("stuff happening");
$scope.Heading = "Hello World";
}]);

Categories