I am trying to get the inner text of a <p> element in my Angular application and pass it to a method and a view using ng-route. So when a user clicks on the <p> element, the innerText is passed through a method, gets some data back, then returns a new view with the response data returned
<p ng-click="searchUser()">Bob Ross</p>
js
var app = angular.module('app', ['ngRoute'])
.config(['$routeProvider', function($routeProvider){
.when('/searchUser:name', {
templateUrl: 'user-results.html',
controller: 'searchController'
})
app.controller('searchController', function($scope, $routeParams) {
$scope.name = $routeParams.name;
$scope.searchUser = function(){
// do some stuff;
}
});
I'm not sure how to grab the inner text of the <p> tag properly and pass it through the method (I'm likely way off); should I be binding it to my model and then passing as a routeparam?
Any help is appreciated!
I'm assuming you're using $http to get the list of users in your controller, in which case you could do this:
<p ng-repeat="user in users" ng-click="searchUser(user.name)">{{user.name}}</p>
And in your controller:
$scope.searchUser = function(userName){
// do some stuff with userName;
};
You can pass in the $event argument to the searchUser function. You can then use the $event.currentTarget to grab the element. For more details on the $event object, click here.
<p ng-click="searchUser($event)">Bob Ross</p>
$scope.searchUser = function($event){
var username = $event.currentTarget.innerHTML;
}
Related
I'm trying to take the first example from the angular.js homepage and adding in cookie support.
This is what I have so far: https://jsfiddle.net/y7dxa6n8/8/
It is:
<div ng-app="myApp">
<div ng-controller="MyController as mc">
<label>Name:</label>
<input type="text" ng-model="mc.user" placeholder="Enter a name here">
<hr>
<h1>Hello {{mc.user}}!</h1>
</div>
</div>
var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', [function($cookies) {
this.getCookieValue = function () {
$cookies.put('user', this.user);
return $cookies.get('user');
}
this.user = this.getCookieValue();
}]);
But it's not working, ive been trying to learn angular.
Thanks
I'd suggest you create a service as such in the app module:
app.service('shareDataService', ['$cookieStore', function ($cookieStore) {
var _setAppData = function (key, data) { //userId, userName) {
$cookieStore.put(key, data);
};
var _getAppData = function (key) {
var appData = $cookieStore.get(key);
return appData;
};
return {
setAppData: _setAppData,
getAppData: _getAppData
};
}]);
Inject the shareDataService in the controller to set and get cookie value
as:
//set
var userData = { 'userId': $scope.userId, 'userName': $scope.userName };
shareDataService.setAppData('userData', userData);
//get
var sharedUserData = shareDataService.getAppData('userData');
$scope.userId = sharedUserData.userId;
$scope.userName = sharedUserData.userName;
Working Fiddle: https://jsfiddle.net/y7dxa6n8/10/
I have used the cookie service between two controllers. Fill out the text box to see how it gets utilized.
ok, examined your code once again, and here is your answer
https://jsfiddle.net/wz3kgak3/
problem - wrong syntax: notice definition of controller, not using [] as second parameter
If you are using [] in controller, you must use it this way:
myApp.controller('MyController', ['$cookies', function($cookies) {
....
}]);
this "long" format is javascript uglyfier safe, when param $cookies will become a or b or so, and will be inaccessible as $cookies, so you are telling that controller: "first parameter in my function is cookies
problem: you are using angular 1.3.x, there is no method PUT or GET in $cookies, that methods are avalaible only in angular 1.4+, so you need to use it old way: $cookies.user = 'something'; and getter: var something = $cookies.user;
problem - you are not storing that cookie value, model is updated, but cookie is not automatically binded, so use $watch for watching changes in user and store it:
$watch('user', function(newValue) {
$cookies.user = newValues;
});
or do it via some event (click, submit or i dont know where)
EDIT: full working example with $scope
https://jsfiddle.net/mwcxv820/
Working with angularJS I am trying to figure out a way to bind the value of a select element under the scope of controller A to use it as an argument for an ng-click call [getQuizByCampID() Function] under the scope of controller B.
My first idea was to use jquery, but I have read in the link below that using jquery is not recommended when starting with angularJS.
"Thinking in AngularJS" if I have a jQuery background?
I also read in the link below that this is performed using ng-model, the only problem is that that the example provided is all under the same controller.
and Binding value to input in Angular JS
What is the angularJS way to get the value of the select element under controller A into the function call in the select under controller B?
Price.html view
<div class="col-sm-3" ng-controller="campCtrl"> **Controller A**
<select id="selCampID" class="form-control" ng-model="campInput" >
<option ng-repeat="camp in campaigns" value="{{camp.camp_id}}">{{camp.camp_name}}</option>
</select>
</div>
<div class="col-sm-3" ng-controller="quizCtrl"> **Controller B**
<select ng-click="getQuizByCampID($('#selCampID').val())" class="form-control" ng-model="quizInput">
<option ng-controller="quizCtrl" ng-repeat="quiz in quizzesById" value="{{quiz.quiz_id}}">{{quiz.quiz_name}}</option>
</select>
</div>
App.js
var app= angular.module('myApp', ['ngRoute']);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
}]);
$routeProvider.when('/price', {templateUrl: 'partials/price.html', controller: 'priceCtrl'});
Quiz Controller
'use strict';
app.controller('quizCtrl', ['$scope','$http','loginService', function($scope,$http,loginService){
$scope.txt='Quiz';
$scope.logout=function(){
loginService.logout();
}
getQuiz(); // Load all available campaigns
function getQuiz(campID){
$http.post("js/ajax/getQuiz.php").success(function(data){
$scope.quizzes = data;
//console.log(data);
});
};
$scope.getQuizByCampID = function (campid) {
alert(campid);
$http.post("js/ajax/getQuiz.php?campid="+campid).success(function(data){
$scope.quizzesById = data;
$scope.QuizInput = "";
});
};
$scope.addQuiz = function (quizid, quizname, campid) {
console.log(quizid + quizname + campid);
$http.post("js/ajax/addQuiz.php?quizid="+quizid+"&quizname="+quizname+"&campid="+campid).success(function(data){
getQuiz();
$scope.QuizInput = "";
});
};
}])
You should store the value in a service.
example:
app.factory('SharedService', function() {
this.inputValue = null;
this.setInputValue = function(value) {
this.inputValue = value;
}
this.getInputValue = function() {
return this.inputValue;
}
return this;
});
Example on Plunkr
Read: AngularJS Docs on services
or check this Egghead.io video
You should use service to store the value.
This is how to do that:
Share data between AngularJS controllers
I am trying to populate the ng-model from a value, but don't want it to update until it is saved. To do this I have the following code;
Controller;
var SettingsController = function (roleService) {
var ctrl = this;
ctrl.rename = function(name) {
ctrl.account.name = name;
};
roleService.role.settings().then(function (result) {
ctrl.account = result.data.account;
}, function (result) {
console.log(result);
});
};
A simple controller, it gets the current settings from a service and sets it to the ctrl.
When the rename(name) is called I update the name of the account (for now it just updates the scope but soon it will update also the back-end)
To rename your account I have the following piece of code
<input type="text" data-ng-model="account.name" />
<button type="button" data-ng-click="ctrl.rename(account.name)">
Rename
</button>
I use controler as so ctrl == SettingsController
Now I use data-ng-model="account.name" to update the name. This is done so I only update the name when the button is called. The only issue is how do I get the ctrl.account.name value to the input, without bubbling it up.
I could add $scope to my controller with $scope.account but that seems overkill to me. Isn't there a way to copy/populate a ng-model from an other value or some kind?
To get to the controller I use the angular routerProvider;
$routeProvider
.when('/settings/', {
templateUrl: '/user/template/settings/',
controller: 'SettingsController',
controllerAs: 'ctrl'
});
I have html page like
<div ng-controller="userListControl">
...
</div>
<div ng-controller="userDetailsControl">
....
</div>
And i have angular Js code is
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", ['$scope','$http', function($scope, $http)
{
$http.get('data/userData.json').success (function(data){
$scope.users = data;
$scope.users.doClick = function(user,event) {
userInfo(user);
}
});
}]);
function userInfo(users)
{
console.log(user);
userDirectory.controller("userDetailsControl", function($scope)
{
console.log('well')
$scope.user = users;
console.log($scope.user)
});
}
Here Everything is working fine. But when we are calling click event, That userInfo called with particular Data. But Second controller gives an error(angular js Error).
I am new one in angular jS. I dont know this logic is correct or not.
I have list items in first Controller. When we are clicking on list, It gets data from particular list and passed to another design. That design have detailed data. So the 2nd controller shows particular list detailed Section
First, There is no need to declare your controller inside a function - I don't think that you're trying to lazy-load controllers. Make it available to your app when it starts.
Second, you need to pass data to the userDetailsControl controller. There are various ways to do this, but here you could just use the $rootScope.
var userDirectory = angular.module('userDirectory',[]);
userDirectory.controller("userListControl", function($scope, $rootScope, $http)
{
$scope.selectUser = function(user){
$rootScope.selectedUser = user;
}
$http.get('data/userData.json')
.success (function(data){
$scope.users = data;
});
})
.controller("userDetailsControl", function($scope, $rootScope){
$rootScope.$watch("selectedUser", function(newVal){
$scope.user = newVal;
}
}
and in your HTML:
<div ng-controller="userListControl">
<button ng-repeat="user in users" ng-click="selectUser(user)">{{user.name}}</button>
</div>
<div ng-controller="userDetailsControl">
<div>{{user.name}}</div>
<div>{{user.otherDetails}}</div>
</div>
In my regular Javascript I append data to HTML ONLY if there's data from the server, otherwise I just show a simple div saying there's nothing. How can I implement this in AngularJS?
Example:
if (AJAXresult)
$element.append(JSONdata); //JSONdata will contain a list of customer data
else
$element.append('<div>No results</div>');
How can I achieve this in Angular?
The simplest way would be to control for the no data state in your returned view.
<div>
<div ng-if="!hasCustomers">
No Customers Available
</div>
<div ng-if="hasCustomers">
<!-- show some stuff -->
</div>
</div>
Then in your controller you can easily initialize this when you load your data:
angular.module('myApp').controller('MyController', function($scope, myDataService){
$scope.hasCustomers = false;
myDataService.getCustomers()
.then(function(value){
$scope.customers = value.data;
$scope.hasCustomers = customers && customers.length;
});
});
If you want to make sure the data is loaded before your view is ever instantiated, then you can also use the resolve property on your $route
$routeProvider.when('/someRoute/',{
templateUrl: '/sometemplate.html',
controller: 'MyController',
controllerAs: 'ctrl', // <-- Highly recommend you do this
resolve: {
customerData: function(myDataService){
return myDataService.getCustomers();
}
}
});
resolve is basically a hash of functions that return a promise, and can be dependency injected just like everything else. The controller and view will not be loaded until all the resolve promises have been fulfilled.
It will be available in your controller by the same property name you gave it:
angular.module('myApp')
.controller('MyController', function($scope, customerData){
$scope.customers = customerData;
$scope.hasCustomers = customerData && customerData.length;
});