AngularJS get parameters from Laravel - javascript

I don't know how to pass a variable from home.blade.php of Laravel to my Controller.js of AngularJS.
LARAVEL:
I have a home.blade.php with a variable searchid:
#extends('layouts.default')
#section('content')
<div class="row" ng-app="app">
{{ $searchid }}
<post-controller></post-controller>
</div>
#stop
This variable is send by controller of Laravel:
class SearchController extends BaseController {
public function makeSearch($searchid)
{
return View::make('pages.search')->with('searchid', $searchid);
}
}
ANGULARJS:
I need to pass this variable to AngularJS controller.
I have a directive file like this:
app.directive('postController', function()
{
return {
restrict: 'E',
templateUrl: 'templates/search.html'
}
});
And controller file like this:
app.controller('SearchController', ['$scope', function($scope, $routeParams)
{
console.log($routeParams.search);
$scope.param = $routeParams.search;
}]);
I don't know how to pass this variable search to my controller.js.

There's a nice package that does nearly all the work for you. PHP-Vars-To-Js-Transformer
However the basic principle is just passing variables to javascript by creating a <script> tag in your view and defining javascript variables. Here's an example:
<script type="text/javascript">
var searchId = {{ $searchId }};
</script>
Attention depending on the data type of your variable you'll have to use quotes around it or maybe even serialize it with json.

Related

Angular Js linking a controller to a route doesn' work

I watching an Angular course on codeschool and it say that there are two way to link a controller to a route
The first one is declaring the controller inside the route like this:
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller: function(){.....}
})
the second way is to create a new file and then, over there, declare all the methods associate to that controller. After this have been done, we have to associate the controller to the route, like this.
angular.module('NotesApp')
.config(function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:' templates/pages/notes/index.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
This controller, I've made, import some data using an ajax call from a json file but it doesn't work well. I have to use this controller inside an HTML file
this is the controller
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('notes.json').success(function(data){
controller.notes = data;
})
}]);
This is the HTML code
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
the html should import all note stored inside the controller.notes array and display all it but it seems like the html doesn't recognize the controller and does't import anything.
The code works just if I declare inside the HTMl the controller I have to use like this:
<div ng-controller="NotesIndexController as indexController">
<a ng-repeat="note in indexController.notes" ng-href="#/notes/{{note.id}}">
<div class="col-md-3 fixHeight" >
<h4>Id: {{note.id}}<h4>
<h4>Title: {{note.title}}</h4>
<h4>Description: {{note.description}}</h4>
</div>
</a>
</div>
My question is. If I declare the controller inside my route why I should declare it also in my HTML?
Ok thanks everybody, I figured out what was the problem. This is the complete route.js file
angular.module('NotesApp',["ngRoute"])
.config(['$routeProvider',function($routeProvider){
$routeProvider.when('/notes', {
templateUrl:'templates/pages/notes/index.html',
controller:'NotesIndexController', // I have to declare the controller inside the template to make it work
controllerAs:'indexController'
})
.when('/users',{
templateUrl: 'templates/pages/users/index.html'
})
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
.when('/notes/:id', {
templateUrl:'templates/pages/notes/show.html',
controller:'NoteShowController',
controllerAs:'showController'
})
.otherwise({redirectTo:'/'});
}]);
The problem was the line:
.when('/',{
templateUrl: 'templates/pages/notes/index.html'
})
instead, to load my controller should have been
.when('/',{
redirectTo: '/notes'
})
Please find this working plunk with your code
angular.module('NotesApp', ["ngRoute"])
.config(function($routeProvider){
$routeProvider.when('/', {
templateUrl:'main.html',
controller:'NotesIndexController',
controllerAs:'indexController'
})
})
angular.module('NotesApp').controller('NotesIndexController',['$http', function($http){
var controller = this;
controller.notes = [];
$http.get('data.json').success(function(data){
console.log(data)
controller.notes = data;
})
}]);

Sharing scope in different views with custom controllers

I've got the next problem and I'd like to find a solution or if I should even be doing this like I am.
I have the following ui-router configuration:
$stateProvider.state('ListCounterparties', {
url:"/counterparties",
data: { NavMenuItem : 'Counterparties / Desks' },
views: {
'' : {
templateUrl:"./app/module_Counterparties/templates/ListCounterparties.html",
controller:"CounterpartiesControllerCtrl"
},
'deskLists#ListCounterparties' : {
templateUrl : './app/module_Counterparties/templates/DesksDualListTemplate.html',
controller:'DesksControllerCtrl'
}
}
The first, unnamed view, has a table from which I can select a row and then a method will be called to populate a dual list from the second view.
Up until now, I've had both in the same controller, but the controller is getting too big and I decided I had to separate them.
The method to populate the dual lists in 'deskLists#ListCounterparties' is defined in DesksControllerCtrl but it should be called in CounterpartiesControllerCtrl, as the event of row selection is in that controller.
The problem is that the scopes are not shared and the method is inaccesible to the unnamed view.
Accessing the scope in DesksControllerCtrl I could see that accessing the $parent property twice I can get to the CounterpartiesControllerCtrl, but I don't thin that's an ideal thing to do.
Thanks in advance.
Sharing data, methods, etc. between multiple controllers the Angular way would be to create service(s). That means, you create e.g. a service which holds all your data and another one which provides functionality for several controllers. Then, just inject them in your controllers:
var myApp = angular.module('myApp', []);
myApp.factory('myGlobalData', function() {
return {
data: 1
};
});
myApp.factory('myService', function(myGlobalData) {
return {
increment: function() {
myGlobalData.data++;
}
};
});
myApp.controller('MyCtrlA', function($scope, myGlobalData, myService) {
$scope.myGlobalData = myGlobalData;
$scope.myService = myService;
});
myApp.controller('MyCtrlB', function($scope, myGlobalData, myService) {
$scope.myGlobalData = myGlobalData;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<p ng-controller="MyCtrlA">
{{myGlobalData.data}}
</p>
<p ng-controller="MyCtrlB">
{{myGlobalData.data}}
</p>
<div ng-controller="MyCtrlA">
<button ng-click="myService.increment()">Increment data in myGlobalData service</button>
</div>
</div>

Angularjs how to pass data from a controller to a directive

I have a controller which gets activated by a route (see below) I would like to create a directive that uses this data (once loaded) but I have no idea how to pass this data/bind it.
This is my controller:
app.controller("CampaignData" , ['$scope', 'Restangular', 'CbgenRestangular', '$http', '$q',
function($scope, Restangular, CbgenRestangular, $http, $q){
var campaign_call = CbgenRestangular.one('api/v1/campaign', "testcamp").get();
$q.when(campaign_call.then(
function(campaign) {
$scope.campaign = campaign;
console.log(campaign);
}
))
.then(function(){
var cars = $http({method: 'GET', url:$scope.campaign.carlot});
cars.then(function(reward){
// do success things here
console.log(reward.data)
},
function(reward){
//do error things here
});
})
}]);
Then in my template I want to do something like this
{{ campaign.name }} {{ car.name }}
or even this
<campaign="name"></campaign>
<campaign="car.name"></campaign>
How can this be done?
I would not like to create a directive that uses this data
There is no need to create a directive. Once you declare a template and controller in the route config, all the scoped properties within the controller will become active for the template.
Interpolation like this should then work fine:
<div>{{ campaign.name }}</div>
<div>{{ car.name }}</div>
If you wanted to handle a click event on one of the divs, it would look like this:
<div ng-click="myFunctionInController(campaign.name)">{{ campaign.name }}</div>
This function would then be defined in the controller like this:
$scope.myFunctionInController = function(name) {
console.log(name);
}

How to render html with AngularJS templates

This is my template:
<div class="span12">
<ng:view></ng:view>
</div>
and this is my view template:
<h1>{{stuff.title}}</h1>
{{stuff.content}}
I am getting the content as html and I want to display that in a view, but all I am getting is raw html code. How can I render that HTML?
Use-
<span ng-bind-html="myContent"></span>
You need to tell angular to not escape it.
To do this, I use a custom filter.
In my app:
myApp.filter('rawHtml', ['$sce', function($sce){
return function(val) {
return $sce.trustAsHtml(val);
};
}]);
Then, in the view:
<h1>{{ stuff.title}}</h1>
<div ng-bind-html="stuff.content | rawHtml"></div>
In angular 4+ we can use innerHTML property instead of ng-bind-html.
In my case, it's working and I am using angular 5.
<div class="chart-body" [innerHTML]="htmlContent"></div>
In.ts file
let htmlContent = 'This is the `<b>Bold</b>` text.';
You shoud follow the Angular docs and use $sce - $sce is a service that provides Strict Contextual Escaping services to AngularJS. Here is a docs: http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe
Let's take an example with asynchroniously loading Eventbrite login button
In your controller:
someAppControllers.controller('SomeCtrl', ['$scope', '$sce', 'eventbriteLogin',
function($scope, $sce, eventbriteLogin) {
eventbriteLogin.fetchButton(function(data){
$scope.buttonLogin = $sce.trustAsHtml(data);
});
}]);
In your view just add:
<span ng-bind-html="buttonLogin"></span>
In your services:
someAppServices.factory('eventbriteLogin', function($resource){
return {
fetchButton: function(callback){
Eventbrite.prototype.widget.login({'app_key': 'YOUR_API_KEY'}, function(widget_html){
callback(widget_html);
})
}
}
});
So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:
<html>
<body ng-app="yourApp">
<div class="span12">
<div ng-view=""></div>
</div>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
Then yourView.html could just be:
<div>
<h1>{{ stuff.h1 }}</h1>
<p>{{ stuff.content }}</p>
</div>
scripts.js could have your controller with data $scope'd to it.
angular.module('yourApp')
.controller('YourCtrl', function ($scope) {
$scope.stuff = {
'h1':'Title',
'content':"A paragraph..."
};
});
Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)
angular.module('yourApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/yourView.html',
controller: 'YourCtrl'
});
});
I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data

AngularJS Controller depending on URL parameter

EDIT: Added $routeProvider and $routeParams, but $routeParams.productId is always undefined. It was my initial try, but I thought it was the wrong way. Anyway it does not work for the moment.
I start to learn AngularJS and I have a very simple question :
Depending on ID contained in URL, I would like to display different BD record.
...
<div ng-app=MyApp>
<div ng-controller="MyCtrl">
{{ record }}
</div>
</div>
...
My Javascript file :
var MyApp = angular.module("MyApp",[]);
MyApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/get/:productId', {
controller: 'MyCtrl'
});
}])
MyApp.controller('MyCtrl',['$scope','$routeParams','$http',
function($scope,$routeParams,$http) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
}])
I tried to use $routeProvider and $routeParams without success.
Thank you in advance,
Bill
you need 2 things , the $routeParams injected in your controller and create a valid route with the get method
MyApp.controller('MyCtrl',['$scope','$http',"$routeParams",
function($scope,$http,$routeParams) {
$http.get("/get/"+$routeParams.productId).success(function(data) {
$scope.record = data;
});
};

Categories

Resources