Angularjs - Using controller - angularjs

I am new to Angular.js. I currently have the following html code, where I define my div with my file html ( ng-include ) and my controller ( ng-controller ):
<div id="customerinformation-maxi" ng-include="'pages/customerinformation-maxi.html'" ng-controller="customerInformationMaxiController" class="col-md-12"></div>
This is the html code for the called html in directive ng-include ( customer-information.html ):
<div class="row">
<div class="col-md-2">
<span>Customer Number</span>
<span>{{customer.number}}</span>
</div>
<div class="col-md-2">
<span>Portfolio</span>
<span>{{custom.portfolio}}</span>
</div>
</div>
This is the js controller:
angularRoutingApp.controller('customerInformationMaxiController', function($scope, $http) {
//Here i need to load the model variable with a literal text {{customer.number}} and {{customer.portfolio}}, how could do it? using scope object? with a json file?
});
Here I need to load the model variable with a literal text {{customer.number}} and {{customer.portfolio}}.
How could do it? Using scope object? With a json file?
Thanks for any help.

Yes, you should do it using the $scope object.
To get a general overview, here is a hello-world example:
<div ng-controller="HelloController">
{{ helloMessage }}
</div>
And in you controller's code (js file or script tag into the html):
var myApp = angular.module('myApp',[]);
myApp.controller('HelloController', ['$scope', function($scope) {
$scope.helloMessage= 'Hello World!';
}]);
But I foresee some nesting in the provided snippet of your question, so you 're probably dealing with a collection of objects which means that you have to iterate through it, in the html part, using the ng-repeat directive, like:
<tr ng-repeat="customer in customers>
<td>{{customer.number}}</td>
<td>{{customer.portfolio}}</td>
</tr>
So, your controller's functionality should contain the customers object, like:
angularRoutingApp.controller('customerInformationMaxiController', function($scope, $http) {
var customers=[
{
number:'123',
portfolio: 'blah blah'
},
{
number:'124',
portfolio: 'blah blah'
},
{
number:'125',
portfolio: 'blah blah'
}
];
});
For further reference, you could read two respective example I have written:
Angular.js Controller Example
Angular.js JSON Fetching Example
The second one is only to see a sample usage of traversing collections, it is not meant that you have to use json, as you stated in your question; but I see that you also defined the $http service in your controller, so if it's about data that are going to be fetched from a remote destination, the JSON Fetching Example should probably help you better).

You should use scope objects to give values to your modal variables.
angularRoutingApp.controller('customerInformationMaxiController', function($scope, $http) {
$scope.customer.number = 'sample number';
$scope.customer.portfolio = 'sample portfolio';
});

Related

$ctrl in data binding is not working

I want to make a dynamic page using angular where the user after he logged-in see his user picture and some information charged by json file throught an http request.
This is the module where i do the http requestes:
'user strict';
angular.
module('userIssue').
component('userIssue',{
templateUrl: 'user-issue/user-issue.html',
controller: 'userIssueCtrl'
})
.controller('userIssueCtrl',['$scope','$http','$routeParams',function userIssueCtrl($scope,$http,$routeParams){
var self = this;
var percorso;
$scope.utente=$routeParams.username;
document.title="Benvenuto"+" "+$routeParams.username;
$http.get('user/'+ $routeParams.username+'.json').then(function(response){
self.utenti = response.data;
});
$http.get('user/'+$routeParams.username+'.info.json').then(function(qualcosa){
self.d = qualcosa.data;
});
self.show = function(){
$scope.showForm='false';
}
}]);
and this is the part of the html page not working:
<div class="col-sm-4">
<img style="position:center;" ng-src="{{$ctrl.d.imgUrl}}" class="img-circle" alt="user image"></div>
I'm using the same approch in this part of the code:
<div class="col-md-9 col-sm-9" id="issueColumn" >
<div id="issue" ng-repeat='utenti in $ctrl.utenti'>
<li>
<dt>CODICE OPERAZIONE</dt>
<dd>{{utenti.id}}</dd>
<dt>DESCRIZIONE PROBLEMA</dt>
<dd>{{utenti.description}}</dd>
<dt>DATA SEGNALAZIONE</dt>
<dd>{{utenti.forward}}</dd>
<dt>IL PROBLEMA SARà RISOLTO ENTRO IL:</dt>
<dd>{{utenti.endstimed}}</dd>
<dt>STATO DEL PROBLEMA:</dt>
<dd>{{utenti.stato}}</dd>
</li> </br>
</div>
</div>
and here it is working! So why does the data binding not work for the image?
Could someone gently explain me why?
Here is the json file I use for the image:
[
{
"imgUrl": "img/Filippo.png",
"ciao": "ciao_calro"
}
]
As you want to use 1st element of d array object, you should be accessing 1st element of imgUrl property explicitly.
ng-src="{{$ctrl.d[0].imgUrl}}"
Hi can you try the below changes from your code and let me know,
Introduced controllerAs with the controller object:
component('userIssue',{
templateUrl: 'user-issue/user-issue.html',
controllerAs: 'userCtrl'
controller: 'userIssueCtrl' })
Accessing through the controller object name:
Try to access through the controller object name like,
{{userCtrl.d.imgUrl}} in template.

AngularJS Communication between ng-repeat and controller

I've just started using AngularJS, and as a project I decided to build a simple app for managing bookmarks. I want to be able to maintain a list of bookmarks and add/remove items. I'm using Django with Django REST framework, and Angular.
So far I've written a service to grab the bookmarks from the database, and I can print them to the console from my controller, but ng-repeat doesn't seem to be seeing them.
Here's my code for the service:
.factory('BookmarkService', ["$http", function ($http) {
var api_url = "/api/bookmarks/";
return {
list: function () {
return $http.get(api_url).then(function (response) {
return response.data
})
}
}
}]);
And for the controller:
.controller("ListController",
["$scope", "BookmarkService", function ($scope, BookmarkService) {
$scope.bookmarks = BookmarkService.list();
console.log($scope.bookmarks);
}]);
And here's the HTML:
<div ng-controller="ListController as listCtrl">
<md-card>
<md-card-content>
<h2>Bookmarks</h2>
<md-list>
<md-list-item ng-repeat="bookmark in listCtrl.bookmarks">
<md-item-content>
<div class="md-tile-content">
<p>{[{ bookmark.name }]} - {[{ bookmark.url }]}</p> // used interpolateProvider to allow "{[{" instead of "{{"
</div>
<md-divider ng-if="!$last"></md-divider>
</md-item-content>
</md-list-item>
</md-list>
</md-card-content>
</md-card>
</div>
When I print to the console from the controller I can see a promise object but ng-repeat isn't repeating:
image of promise object
I'd really appreciate if someone could help me to find my mistake and to understand why it is happening. I'm still not entirely comfortable with how all these parts fit together.
Thanks for your time!
There's two problems that I see with the code in question.
The first is that using the controller as syntax (ng-controller="ListController as listCtrl") requires properties to be bound to the controller instance and not to the scope if you address them using the controller name. In your case,
.controller("ListController",
["BookmarkService", function (BookmarkService) {
this.bookmarks = BookmarkService.list();
console.log(this.bookmarks);
}]);
The second is that you are assigning a promise to your $scope.bookmarks property. The repeater is expecting an array of objects to iterate over. You really want to assign the value resolved by the promise to $scope.bookmarks.
Instead of this
$scope.bookmarks = BookmarkService.list();
Do this
BookmarkService.list().then(function(result){
this.bookmarks = result;
});
The final version of your controller should look something like this
.controller("ListController",
["BookmarkService", function (BookmarkService) {
this.bookmarks = BookmarkService.list();
console.log(this.bookmarks);
}]);
This is simple. Ng-repeat is not working with promises. So, you can go with two ways:
BookmarkService.list().then(function(responce){
$scope.bookmarks = responce.data;
});
Another way is to create own repiter ^)
Ng-repeat doc

Angularjs: parent and child scope

point 1
i just do not understand why i could not access child controller property this way {{$scope.parentcities}}. but if i write like this way {{parentcities}} then it is working. so why we can not write $scope dot and then property name
<div ng-app ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl as vm">
{{$parent.cities}}
<br>
{{$scope.parentcities}}
</div>
</div>
function ParentCtrl($scope) {
$scope.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl($scope) {
$scope.parentcities = $scope.$parent.cities;
}
point 2
need some guide line what kind of syntax it is ChildCtrl as vm ?
when we need to mention controller in html ChildCtrl as vm like this way ?
does it carry any special meaning?
looking for some guidance. thanks
Well, the point of $scope is that you don't need to write it when you bind values to the view. So $scope.supervalue = 'Hallo' will be accessed in the view like this {{ supervalue }}. That's it.
$parentis a keyword from the Angular framework to reference the parent scope.
The controllerAs syntax is made to get rid of the $scope keyword alltogether. So inside the controller, you can write it like this:
var self = this;
self.supervariable = 'Hallo';
In your config for this route, you specifiy controllerAs: 'vm'. So you can access your values in the view via {{ vm.supervariable }}. Have a look here to learn all about it.
But, it seems like you should do some groundwork first and learn about the basic Angular mechanism before you dive into controllerAs, which has some tricky parts to it later on.
As long as you are going to use Ctrl as c syntax please assign values to this variable
function ParentCtrl($scope) {
$scope.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl($scope) {
this.parentcities = $scope.$parent.cities;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl as vm">
{{$parent.cities}}
<hr>
{{vm.parentcities}}
</div>
</div>

angularjs dynamic model in directive from json object

I have a json file of objects that store the properties to be used in a directive.
I want to use the json obj model value in the directive, but nothing I am trying is working.
Anyone have any ideas what I am doing wrong / missing? I find this very confusing.
Hope someone can help been trying this for days now!
Edit::
I have a $http service that gets and returns the Json object and I can access the properties fine.
I am specifically trying to use the value of the json obj model property -- "model" : "ticketData.contactname" as the dynamic value of the ng-model.
If I just use the ticketData.contactname obj then it works fine and I can edit the model value, but if I try and use the string from the Json obj then it just prints the string into the input box.
I do not know what to do. I am sure it is something basic I am missing.
Thanks in advance
Json sample:
[
{
"inputsContact" : [
{
"labelName" : "Contact Name",
"placeholder" : "Enter your name",
"model" : "ticketData.contactname",
"type" : "text"
}
}
]
Html sample:
<text-input-comp inputdata="contactName" ng-model="contactModel"> </text-input-comp>
Directive text-input-comp:
.directive('textInputComp', [ '$compile', function($compile){
return {
restrict: 'E',
scope: {
inputData: '=inputdata',
modelData: '=ngModel'
},
templateUrl: '/app/views/partials/components/textInputComp.html'
}
}]);
Directive template sample:
<label> {{ inputData.labelName }} </label>
<input type="text" ng-model="modelData" ng-model-options="{ getterSetter: true }" placeholder="{{ inputData.placeholder }}" />
<div ></div>
Controller sample:
$scope.contactName = $scope.inputData[0].inputsContact[0];
$scope.contactModel = $scope.inputData[0].inputsContact[0].model;
i think u need to get the json file first then do all the manupilation
have a look at this code
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("customers.json").then(function (response) {
$scope.myData = response.data.records;
});
});
</script>
</body>
</html>
What u were missing is this
Just replace the customer.json file with your json and u are good to go
and
1.$http is service responsible for communicating with other file. $http says get file from ‘js/data.json’ and if the operation is a ‘success’ then execute a function holding the ‘data’ which it got automatically from data.json file
to make u understand.
2.A one more line above: [‘$scope’, ‘$http’, function($scope, $http){ … }] is little bit tricky: it takes an array holding two objects one is $scope and other is a service i.e $http. The reason we have this in array is angularJS automatically minifies code which means it removes extra spaces and shorten variable names for faster performance but sometimes this minification causes trouble so we just told controller NOT to minify $scope, $http services and function inside array.

Preserving Scope in ng-repeat ( not wanting child scope )

I might be missing something conceptually but I understand that ng-repeat creates child scopes but for my scenario this is undesirable. Here is the scenario. I have a 3way bind to a firebase dataset. The object is an object with n sub objects. In my current code structure I use ng-repeat to iterate and render these objects with a custom directive. The issue is that these objects are meant to be "live" ( meaning that they are 3-way bound. The highest level object is bound with angularfire $bind ).
So the simple scenario in my case would be where the ng-repeat created scope was not isolated from the scope that it was created from.
I am looking for ideas on how to do this? Or suggestions on other approaches.
This won't be a complete answer, but I can help with the angularFire portion, and probably an angular guru can fill in the blanks for you (see //todo).
First of all, don't try to share scope. Simple pass the variables you want into the child scope. Since you'll want a 3-way binding, you can use & to call a method on the parent scope.
For example, to set up this pattern:
<div ng-repeat="(key,widget) in widgets">
<data-widget bound-widget="getBoundWidget(key)"/>
</div>
You could set up your directive like this:
.directive('dataWidget', function() {
return {
scope: {
boundWidget: '&boundWidget'
},
/* your directive here */
//todo presumably you want to use controller: ... here
}
});
Where &boundWidget invokes a method in the parent $scope like so:
.controller('ParentController', function($scope, $firebase) {
$scope.widgets = $firebase(/*...*/);
$scope.getBoundWidget = function(key) {
var ref = $scope.widgets.$child( key );
// todo, reference $scope.boundWidget in the directive??
ref.$bind(/*** ??? ***/);
};
});
Now you just need someone to fill in the //todo parts!
You still have access to the parent scope in the repeat. You just have to use $parent.
Controller
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.someParentScopeVariable = 'Blah'
$scope.data = [];
$scope.data.push({name:"fred"});
$scope.data.push({name:"frank"});
$scope.data.push({name:"flo"});
$scope.data.push({name:"francis"});
}]);
HTML
<body ng-controller="MainCtrl">
<table>
<tr ng-repeat="item in data | filter: search">
<td>
<input type="text" ng-model="$parent.someParentScopeVariable"/>
<input type="text" ng-model="item.name">
</td>
</tr>
</table>
</body>
Plunker

Resources