Controller data not passed to directive - javascript

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"
}

Related

Angularjs and ui-grid - add event keypress in cell

First of all, I want to say that I am beginner with angularjs :D
My problem is:
I'm trying add the keypress event when user goes to edit the value in cell on angular ui-grid.
In the beginning it seems to work, but when I finish editing a cell and mute the focus the value disappears.
Here is the link to see the event running: https://plnkr.co/edit/vw8W6PqFt11nt4BDhWu9
And here is my code:
File: index.html
<!doctype html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js"></script>
<script src="//cdn.rawgit.com/angular-ui/bower-ui-grid/v3.0.6/ui-grid.min.js"></script>
<link rel="stylesheet" href="//cdn.rawgit.com/angular-ui/bower-ui-grid/v3.0.6/ui-grid.min.css" type="text/css" />
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<div id="grid1" ui-grid="gridOptions" ui-grid-edit class="grid"></div>
</div>
<script src="app.js"></script>
</body>
</html>
File: app.js
(function() {
var app = angular.module('app', ['ui.grid', 'ui.grid.edit']);
app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
$scope.gridOptions = {
columnDefs: [{
field: 'name'
}, {
field: 'amount',
name: 'Number'
}, {
field: 'someValue',
name: 'SomeValue',
editableCellTemplate: 'template-cell.html'
}]
};
$http.get('data.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
}]);
app.directive('numbersOnly', function () {
return {
require: 'ngModel',
link: function (scope, element, attr, ngModelCtrl) {
function fromUser(text) {
if (text) {
var transformedInput = text.replace(/[^0-9]/, '');
if (transformedInput !== text) {
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
}
return transformedInput;
}
return undefined;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
});
}());
File: cell-template.html
<div>
<form name="inputForm">
<input type="text"
ui-grid-editor
ng-model="someValue"
data="row.entity.someValue"
ng-class="'colt' + col.uid"
numbers-only />
</form>
</div>
I need this functionality with keypress event only. How do I update the model with the input field value ?
Thanks.
The problem is that your column value is not correctly bound to the ngModel in the cell template.
The correct value would be to use the MODEL_COL_FIELD which you can read more about in the wiki, look at section "Editable Cell Templates"
Update your cell-template.html to
<div>
<form name="inputForm">
<input type="text"
ui-grid-editor
ng-model="MODEL_COL_FIELD"
ng-class="'colt' + col.uid"
numbers-only />
</form>
</div>

AngularJS two way data binding not working

I am having trouble with two way data binding, I fetch an array of objects from the controller and when I make another request trying to submit part of the data, It goes back and is undefined in the controller when I use console.log,
The app uses AngularJS 1.5.8 and angular-route
Can someone please help me figure out why the console.log in the register scope function logs undefined instead of the names. The code
My index file:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src='lib/angular.min.js'></script>
<script type="text/javascript" src='lib/angular-route.js'> </script>
<script type="text/javascript" src='app.js'></script>
<script type="text/javascript" src='controllers.js'></script>
<title></title>
</head>
<body ng-app='myApp'>
<div ng-view>
</div>
</body>
</html>
The partial I am using is home.html:
<section ng-controller='MyCtrl'>
{{test}}
<form>
<input type="text" name="test" ng-model='post'>
<input type="submit" name="sub" value="post" ng-click='getdata()'>
</form>
<table ng-repeat='i in list'>
<tr>
<td>{{i.name}}</td>
<td>{{i.job}}</td>
<form>
<input type="text"
name="regname" value='{{i.name}}' \ng-model='{{i.name}}' hidden>
<td><input type="submit" name="sub2" ng-click='register()'></td>
</form>
</tr>
</table>
</section>
The app is declared in app.js:
(function () {
// body...
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'MyCtrl'
}).when('/home', {
templateUrl: 'home.html',
controller: 'MyCtrl'
})
})();
The controller code is in controllers.js:
var app = angular.module('myApp');
app.controller('MyCtrl',
['$scope', '$http', function ($scope, $http) {
// body...
$scope.test = 'the test is running';
$scope.getdata = function(){
var item = $scope.post;
console.log(item);
$scope.list = [{'name': 'shem', 'job':'engineer'},
{'name': 'Reinhard', 'job': 'devops'}]
}
$scope.register = function(){
console.log($scope.regname);
}`enter code here`
}]);
Because you are using
console.log($scope.regname);
that isn't existing in your scope. In fact, in your HTML you have
<input type="text" name="regname" value='{{i.name}}' \ng-model='{{i.name}}' hidden>
But regname is only the name of the input, not a binding to your scope.
The solution
Replace your ng-click register() with:
<input type="submit" name="sub2" ng-click="register(i.name)">
and then your register function should be:
$scope.register = function(name){
console.log(name);
}
P.S.
No need to use {{}} brackets in ng-model (ng-model='{{i.name}}'). Replace it with
ng-model="i.name" as shown in the docs.

How to use multiple ng-apps with multiple controllers

Here i have two ng-apps and there controllers.Here is i want to access controller value in other controller with there different ng-apps .But i am getting error.please help me out.
Thank you.
Html:-
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="service.js"></script>
</head>
<body>
<div id="myDiv1">
<div ng-app="mainApp" ng-controller="CalcController">
<p>Enter a number: <input type="number" ng-model="number" />
<button ng-click="multiply()">X<sup>2</sup></button>
<p>Result 1: {{result}}</p>
</div>
</div>
<div ng-app="myDiv2">
<div ng-controller="MyController2">
<p>Enter a number: <input type="number" ng-model="numberSecond" />
<button ng-click="multiplyValue()">X<sup>2</sup></button>
<p>Result 2: {{result2}}</p>
</div>
</div>
</body>
</html>
Controller.js:
angular.module('myReuseableMod',[]).factory('$myReuseableSrvc',function() {
var factory = {};
factory.multiply = function(a) {
return a * a
}
return factory;
});
var mainApp = angular.module("mainApp", ["myReuseableMod"]);
mainApp.controller('CalcController', ['$scope', '$myReuseableSrvc',function($scope, $myReuseableSrvc) {
$scope.multiply = function() {
$scope.result = $myReuseableSrvc.multiply($scope.number);
}
$scope.aB=function()
{
alert("hiii");
}
}]);
var mainApp2 = angular.module("mainApp2", ['mainApp']);
mainApp2.controller('MyController2',['CalcController' '$scope','$myReuseableSrvc',function(CalcController,$scope, $myReuseableSrvc) {
console.log('init B');
$scope.multiplyValue = function() {
$scope.result2 = $myReuseableSrvc.multiply($scope.numberSecond);
CalcController.aB(); //here i want to acess controller 'CalcController' method.
}
}]);
Here is my plunker:
http://plnkr.co/edit/6QyDuV330YlgXy16S2YX?p=preview
You have to manually bootstrap them.
See :
Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application http://docs.angularjs.org/api/ng.directive:ngApp

Pass hidden values to JSON using AngularJS

Im basic developer , just wanted to pass hidden values from my html page in a json array . Following is my code :-
Index.html
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="WorkingCtrl">
<h1 ng-bind="vm.heading"></h1>
<form name="myForm" novalidate>
<b> Text: </b>
<input ng-model="form.text" required /><br>
<button ng-click="submitForm()" bng-disabled="myForm.$invalid">Click Me!</button>
</form>
<p ng-bind="showValues"></p>
</div>
</body>
</html>
app.js
var app = angular.module('myApp');
app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.form = {};
$scope.submitForm = function () {
$scope.showValues = JSON.stringify($scope.form);
}
}]);
Now , the value from ng-model="form.text" successfully returns the result as for unhidden input types
{ "text":"What_ever_text" }
but how to send a defined value in array, consisting of hidden input type like :-
<input value="99999" type="hidden" ng-model="form.userid" required />
So , wanted desired output like :-
{ "text":"What_ever_text" , "userid":"99999" }
any solution ?
Note :- The input type should be hidden or any other easier method appreciated. Thanks in advance.
hidden input fields also works same as normal fields only.
see the below code
var app = angular.module('myApp', []);
app.controller('WorkingCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.form = {
text: "some test",
userid: '12312312312'
};
$scope.submitForm = function () {
$scope.showValues = JSON.stringify($scope.form);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="WorkingCtrl">
<h1 ng-bind="vm.heading"></h1>
<form name="myForm" ng-submit="submitForm()" novalidate>Text:
<input ng-model="form.text" required />
<br/>
<input type="hidden" ng-model="form.userid" required />
<button bng-disabled="myForm.$invalid">Click Me!</button>
</form>
<p ng-bind="showValues"></p>
</div>
</div>

Naming ng-app breaks data-binding in angularjs

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"

Categories

Resources