pass an ID to next page after clicking a link in angularjs - javascript

I have a list of places that I am printing list of places, and the idea is when the user clicks on the place it takes the user to another page where the details of the place can be viewed. How can I achieve this?
HTML:Page1
<li ng-repeat="place in places.places">
{{place.name}}
</li>
Page2:
<table ng-controller="UncatCtrl">
<tr>
<td>Name: </td><td>{{place.place.name}}</td>
</tr>
<tr>
<td>placeID: </td><td ng-model="PlaceID">{{place.place.placeID}}</td>
</tr>
</table>
Angular:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/uncatdetails', {
templateUrl: 'templates/uncatpost.html',
controller: 'UnCatPostCtrl'
})
}])
.controller('UnCatPostCtrl', function ($scope, $http) {})
.controller('UncatCtrl', function ($scope, $http) {
$http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data, status, headers) {
$scope.places = data;
console.log(data);
$scope.message = 'Uncategorised places';
})
$scope.showplace = function(placeID) {
$http({method: 'GET', url: 'http://94.125.132.253:8000/getitemdata?ID=' + placeID}).
success(function(data, status, headers, config) {
$scope.place = data; //set view model
console.log(data);
console.log(placeID);
$scope.view = 'templates/detail.html';
})
.error(function(data, status, headers, config) {
$scope.place = data || "Request failed";
$scope.status = status;
$scope.view = 'templates/detail.html';
});
}
})

try it
.when('/uncatdetails/:id', {templateUrl: 'ftemplates/uncatpost.html',
controller: 'UnCatPostCtrl'})
in your HTML
ng-href="uncatdetails/{{place.placeID}}"
in your controller, add this inject $routeParams
$scope.id = $routeParams.id;

Related

Angular - Break line text

I can't save break line text into my database, how to solve this issue?
My save data suppose to be like this
I want to ask something.
Can I?
Not like this
I want to ask something. Can I?
html
<textarea name="" cols="" rows="" class="form-control" ng-model="rule.message" required></textarea>
<button type="submit" class="btn btn-default" ng-click="create()">Save</button>
js
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + $scope.rule.message
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);
Just use the encodeURIComponent() function to encode the newlines correctly into the URL so it will be seen by the server correctly when you submit the GET request.
So your JS becomes:
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + encodeURIComponent($scope.rule.message)
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);

Pass ng-data to scope

I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});

AngularJS : accessing global variable within html template

I am writing an angularJs app:
html :
<div ng-controller=NavCtrl>
<h1 ng-bind-html="currentTitle"></h1>
</div>
I am searching for a way to update the currentTitle variable in my html which is in global scope.
.service('WorkService', [function(){
return {
currentTitle : 'dada'
};
}])
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
$scope.works = [];
$http({method: 'GET', url: '/api/v1/work'}). //collects all works
success(function(data, status, headers, config) {
$scope.currentTitle = WorkService.currentTitle;
})
})
.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {
$http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
success(function(data, status, headers, config) {
$scope.activateButton($routeParams.workId);
WorkService.currentTitle = data.title;
})
})
But currentTitle variable is not updated in the template. What am i doing wrong?
When you do WorkService.currentTitle = data.title current scope is unaware of this change. That is why you wont see the change in the template.
It is not ideal but for this requirement you may keep the currentTitle in $rootScope and keep update $scope.currentTitle in each controllers and that will do.
.run(function($rootScope){
$rootScope.globalData = {currentTitle : 'dada'}
})
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
$scope.works = [];
$http({method: 'GET', url: '/api/v1/work'}). //collects all works
success(function(data, status, headers, config) {
$scope.globalData.currentTitle = 'New title';
})
})
.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {
$http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
success(function(data, status, headers, config) {
$scope.activateButton($routeParams.workId);
$scope.globalData.currentTitle = data.title;
})
})
And in html
<h1 ng-bind-html="globalData.currentTitle"></h1>
You can't two-way bind to a variable in a service, but you can bind to an accessor function. Change your service to return getter and setter functions:
.service('WorkService', ['$sce', function($sce){
var currentTitle= $sce.trustAsHtml('dada');
return {
getCurrentTitle: function(){ return currentTitle; },
setCurrentTitle: function(value){ currentTitle = $sce.trustAsHtml(value);}
};
Then in your controller you can get the currentTitle like this:
$scope.currentTitle = WorkService.getCurrentTitle;
Note that you are setting it equal to the getCurrentTitle function itself (not the result of the function).
Now your html looks like this:
<h1 ng-bind-html="currentTitle()"></h1>
No need to set up $watches or hang stuff of $rootScope. See Demo here.

Having trouble getting a factory to be recognized in angular controller

I'm trying to pass data from one controller to another using a factory and for some reason my factory isn't getting recognized in angular seed. Here is my app.js file which I'm declaring my factory
var myApp = angular.module('myApp', ['myApp.controllers','angularFileUpload', 'ngRoute']);
//
//
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/' ,{templateUrl:"/syncproto/partials/videoSlides.html"}, "sync").
when('/scenarios', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl").
when('/scenarios/:id', {templateUrl:"/syncproto/partials/scenarios.html"}, "scenariosCtrl")
}]);
myApp.factory('Data', function() {
var Data;
return {
getData: function () {
return Data;
},
setData: function(value) {
Data = value;
}
};
});
Here is the controller which I'm using the factory Data
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data) {
$scope.scenarios = [];
$scope.thumbnails = [];
$scope.init = function(){
console.log('init hit');
$http({ method: 'GET', url: 'http://localhost:3000/scenarios' }).
success(function (data, status, headers, config) {
angular.forEach(data, function(scenario) {
if (scenario.video.length != 0 && scenario.video[0].thumbnailLocation != undefined){
$scope.thumbnails.push(scenario.video[0].thumbnailLocation);
//console.log('thumbnail is' + scenario.video.thumbnailLocation);
$scope.scenarios.push(scenario);
console.log(scenario.video[0].thumbnailLocation);
}
});
//console.log($scope.scenarios);
console.log('success');
}).
error(function (data, status, headers, config) {
console.log('error');
});
console.log($scope.thumbnails);
}
$scope.showVideo = function(scenario){
Data.setData(scenario);
$location.path('/');
//Data.setData($scope.scenarios[$scope.thumbnail.indexOf(thumbnail)]);
}
}])
The problem is that in $scope.showVideo = function(scenario) when i call Data.setData(scenario); I get the error TypeError: Object #<Object> has no method 'setData'
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, Data)
You're missing one argument for the $location service here. It should be
.controller('scenariosCtrl', ['$scope', '$http', '$location', 'Data', function($scope, $http, $location, Data)

Can I change which JSON file is loaded by sending a variable to AngularJS?

I would like to load the content of one of two JSON files, food1.json or food2.json. I am trying to do this from the html template:
<body ng-controller="MainCtrl" ng-init="init('food1')">
And then in the JS:
$scope.init = function (name) {
$scope.name = name;
$scope.category = name + ".json";
$scope.foodlist = {};
$http({
method: 'GET',
url: $scope.category,
}).success(function (data, status, headers, config) {
{
$scope.foodlist = data;
}
}).error(function (data, status, headers, config) {
// something went wrong :(
});
};
});
The category name is properly assembled: I get "I am food1" if I print I am {{ category }}. But no food items are printed. I think I am doing the JSON call wrong.
Here's my Plunkr
You have not injected $http in the controller. Change you code as
app.controller('MainCtrl', function($scope, $http) {
instead of
app.controller('MainCtrl', function($scope) {
DEMO

Categories

Resources