I am trying to store templates in different html files and load them.
What I am trying to achieve is, when the dropdown is changed, I need to load the particular html file. But it is not even hitting the controller of the file i am loading. What am i doing wrong
Index.html
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="angular.min.js"></script>
<script src="Menu.js"></script>
<div ng-app="MenuApp">
<div ng-controller="MainMenu">
<div ng-include src="getView()"></div>
<select ng-model="Template" ng-change="ChangeTemplate()">
<option value="ListItems">ListItems</option>
<option value="BorderedItems">BorderedItems</option>
</select>
</div>
</div>
ListItems.html (sample template)
<div ng-app="Menu">
<div ng-controller="LoadMenu">
<ol ng-repeat="items in MenuItems">
<li>{{item}}</li>
</ol>
</div>
</div>
Menu.js
(function () {
angular
.module('MenuApp', [])
.controller('MainMenu', MainMenuControllerFunction)
.factory('LoadMenu',['$http',LoadingMenuItemsService]);
function MainMenuControllerFunction($scope, $http, $templateCache) {
$scope.Text = "Hello";
$scope.MenuItems = getMenuItems();
function getMenuItems() {
$http.get("https://gist.githubusercontent.com/vigneshvdm/dc8632bde4e010336356/raw/4fe500385f3249b8bc717d5022c50abb0e07ba75/news").then(function (response) {
$scope.MenuItems=response.data.array;
});
};
$scope.ChangeTemplate = function () {
var template = $templateCache.get('../Html/'+$scope.Template+'.html');
};
$scope.getView = function () {
return "ListItems.html";
};
};
function LoadingMenuItemsService() {
var MenuItems;
$http.get("https://gist.githubusercontent.com/vigneshvdm/dc8632bde4e010336356/raw/4fe500385f3249b8bc717d5022c50abb0e07ba75/news").then(function (response) {
MenuItems=response.data.array;
});
return MenuItems;
};
function ConsumeMenu() {
//$scope.MenuItems = MenuApp.LoadMenu;
alert("");
};
angular.module('Menu', ['MenuApp'])
.controller('LoadMenu', ConsumeMenu);
})();
Do not use functions in templates when you can avoid this.
<select ng-model="template">
<option value="test.html">first</option>
<option value="test2.html">second</option>
</select>
<div ng-include="template"></div>
http://plnkr.co/edit/osB9UiSzvF4IoqkizcOP?p=preview
I think you should use angularjs directives in this case. By using them you could store templates in different html files.
Related
I have an existing django web api with angular frontend, using which i can upload images and display them to the user.Now i want to extend this.On clicking the button "segment"(see image) it should pass the corresponding image to my python script on the backend, which does some processing on the image.
I have my python script in the views.py file of the main app,which is some thing like this:
from django.shortcuts import render
def segment_image(request):
if request.method == 'GET':
form = segment_form()
else:
if form.is_valid():
info = request.POST['info_name']
output = script_function(info)
''' Here i am calling script_function,passing the POST data info to it'''
return render(request, 'your_app/your_template.html', {
'output': output,
})
return render(request, 'your_app/your_template.html', {
'form': form,
})
'''here info is our image in some format'''
def script_function(info):
...
'''here goes my mian logic to process the image.'''
...
return x,y,w,h
I have never worked with images as inputs in angular,i dont know how to route the image using angularjs to my view.Now how can i implement this segmentImage() function in app.js file so that the function would call the corresponding view by passing this image as a POST argument.
Below is my index.html file.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<!-- Include Angular and several angular libraries -->
<script src="node_modules/angular/angular.min.js"></script>
<script src="node_modules/angular-resource/angular-resource.min.js"></script>
<!-- Include our app -->
<script src="js/app.js"></script>
<!-- Include our own controllers, factories, directives, etc... -->
<script src="js/filesModelDirective.js"></script>
<script src="js/images.rest.js"></script>
<!-- Include Bootstrap CSS -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!-- Main Division -->
<div class="container-fluid">
<div ng-app="imageuploadFrontendApp" ng-controller="MainCtrl">
<!-- Panel for Uploading a new Image -->
<div class="panel panel-default">
<div class="panel-body">
<form class="form" name="form" ng-submit="uploadImage()">
<label for="inputFile">Select Image:</label>
<input id="inputFile" type="file" files-model="newImage.image">
<br />
<button class="btn btn-default" type="submit">
Upload
</button>
<br />
</form>
</div>
</div>
<div ng-if="images.length == 0">
There are no images available yet.
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-4" ng-repeat="image in images track by image.pk">
<h3>
Image {{ image.pk }}
<button class="btn btn-warning" ng-click="deleteImage(image)">Delete</button>
<button class="btn btn-primary" ng-click="segmentImage(image)">Segment</button>
</h3>
<a href="{{ image.image }}">
<img class="img-responsive" ng-src="{{ image.image }}">
</a>
</div>
</div>
</div>
</div>
</body>
</html>
Below is my app.js file:
// create a module called imageuploadFrontendApp, which relies on ngResource
var myApp = angular.module('imageuploadFrontendApp', ['ngResource']);
// Configure ngResource to always use trailing slashes (required for django)
myApp.config(function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
});
// Main Controller
myApp.controller('MainCtrl', function($scope, Images)
{
console.log('In main Control');
$scope.images = Images.query();
$scope.newImage = {};
$scope.uploadImage = function()
{
// call REST API endpoint
Images.save($scope.newImage).$promise.then(
function(response) {
// the response is a valid image, put it at the front of the images array
$scope.images.unshift(response);
},
function(rejection) {
console.log('Failed to upload image');
console.log(rejection);
}
);
};
$scope.deleteImage = function(image)
{
image.$delete(
function(response)
{
// success delete
console.log('Deleted it');
// update $scope.images
$scope.images = Images.query();
},
function(rejection)
{
console.log('Failed to delete image');
console.log(rejection);
}
);
};
});
You can try some thing like this
Define a url for your view function
urls.py
url(r'^image/script_function/$', script_function, name="script_function")
Write the view for the url script_function
views.py
def script_function(info):
...
'''here goes my mian logic to process the image.'''
...
return x,y,w,h
app.js
$scope.segmentImage = function(image){
$http({method:'POST', url:'https://127.0.0.1/image/script_function/', data:{'image': image}}).
then(function successCallback(response) {
console.log('Image Posted successfully')
},function errorCallback(response) {
console.log('Image Post failed')
}
});
};
Pass the image to the sever via post and process your image.
I'm new at angularjs and i'm having some serious problems lol...
I've something like this that is working so i don't know whats the problem with this code.. can you help me pls?
Here is it: Basicly the scope.create does not work.. it doesn't even enter in the function..
<!DOCTYPE html>
<html>`enter code here`
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-resource/1.6.5/angular-resource.min.js"></script>
<script>
var app = angular.module('myAppDevice', ['ngResource']);
app.controller('deviceCtrl', ['$scope', '$resource', function($scope,$resource) {
$scope.create = function(a){
console.log("ola");
Device = $resource(
"http://localhost:8080/userapi/postdevice/:userId/:deviceType",
{},
{save: {method:'POST',isArray:false, params: {userId: '#userId',deviceType:'#deviceType'}}}
);
$scope.Message = Device.save({externalId: $scope.deviceForm.userId, deviceType:a});
$scope.deviceForm.userId = "";
};
}]);
function func(){
console.log("ole");
}
app.controller('deviceCtrl', function($scope) {
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
</script>
</head>
<body ng-app="myAppDevice">
<div ng-controller="deviceCtrl">
<form name="deviceForm">
<div class="form-group">
<img id="device" alt="sensor"
src="http://www.solucoesindustriais.com.br/images/produtos/imagens_10048/p_sensor-de-movimento-para-porta-12.jpg"
width="300" height="150" ng-click="toggle()" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<div class="form-group">
<p ng-show="myVar">
userId: <input ng-model="deviceForm.userId" type=text>
</p>
</div>
<div class="btn-wrapper">
<div class="row-gutter-5">
<div class="col-md-4 col-xs-6 col-sm-6">
<button class="btn btn_blue" type="button"
data-ng-click="create(lamp)" id="Create">Create</button>
</div>
</div>
</div>
</form>
</div>
</body>
</html>
Thanks
[EDIT] Thanks guys!! it was solved by removing the controller as you said.. i was starting to be desperate !!
you are duplicating your controller by calling twice "deviceCtrl". Keep it once and try. As the code compiles and execute the latest deviceCtrl will get called and hence the $scope.create() not getting called.
Just remove Second deviceCtrl
app.controller('deviceCtrl', function($scope) {
$scope.myVar = false;
$scope.toggle = function() {
$scope.myVar = !$scope.myVar;
};
});
Here is an working example.
So I am completely new to AngularJS and followed a course and started "learning" this framework. I watched the 2 screencasts at the top of this page:
https://github.com/curran/screencasts/tree/gh-pages/introToAngular
After watching both screencasts and looking into some of the examples I tried to create my own simple Angular application where I tried to work with some controllers. Now I have the following code:
Index.html
<html ng-app="WIMT">
<head>
<title>trying out angularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript" src="../bower_components/angular/angular.min.js"></script>
<script type="text/javascript" src="../JS/app.js"></script>
</head>
<body>
<div ng-controller="controllerA as a">
{{a.varA}}
</div>
<div ng-controller="controllerB as b">
{{b.varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
</body>
</html>
JS
(function() {
var app = angular.module('WIMT',[]);
app.controller('controllerA',function($scope,$http){
$scope.varA = "A";
});
app.controller('controllerB',['$scope',function($scope) {
$scope.varB = "B";
}
]);
app.controller('controllerC',function($scope, $http) {
var reg = this;
reg.varC = "C";
});
})();
After I tried to bind varA to the scope in controller A I found out that it didn't work and I looked for a solution on the internet. I have found a few different ways (B & C) that should (could?) work. Only option C works and shows C when I run the html. Both A & B show nothing.
Why do option A and B not work in this example?
Because you are using controllerAs syntax, that's why the third one is working and first two are not.
<div ng-controller="controllerA as a">
{{a.varA}}
</div>
<div ng-controller="controllerB as b">
{{b.varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
If you want the a.varA and b.varB to print, you have to change to below:
<div ng-app="app">
<div ng-controller="controllerA as a">
{{varA}}
</div>
<div ng-controller="controllerB as b">
{{varB}}
</div>
<div ng-controller="controllerC as c">
{{c.varC}}
</div>
</div>
http://jsfiddle.net/t0hhp5wz/
this is pretty the same thing :
app.controller('controllerA',function($scope,$http){
$scope.varA = "A";
});
this syntax will work if you use minification, the previous not.
app.controller('controllerB',['$scope',function($scope) {
$scope.varB = "B";
}
]);
use this syntax in the view :
<div ng-controller="controllerA">
{{varA}}
</div>
since you are using controller as alias, option A & B are placed inside controller scopes which are childScopes of $scope.
if you console.log the $scope you will see option A & B created inside controller scope and not in $scope which is parent scope for those controllers.
I am making a web application using AngularJS and Laravel. The application is meant to allow the user to post a note on a board. With the code I have, when submitting the note it gets saved to the database but it does not display on the page.
angulartest.blade.php:
<!doctype html>
<html lang="en" ng-app="app">
<title>Test angular</title>
<link rel="stylesheet" href="css/bootstrap.css">
<body>
<div class="container" ng-controller="NoteController">
<h3>Add note</h3>
<form ng-submit="addNote()">
<input type="text" ng-model="newNote.content">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<ul>
<li ng-repeat="note in notes">
#{{ note.content }}
</li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
app.js
var app = angular.module('app', ['ngRoute']);
app.factory('Data', function Data($http) {
return {
getNotes: function getNotes() { return $http.get('/notes/all'); },
addNote: function addNote(data) { return $http.post('/notes', data); },
removeNote: function removeNote(id) { return $http.delete('/notes?id='+ id); }
}
});
app.controller('NoteController', function NoteController($scope, Data) {
Data.getNotes().success(parseNotes);
function parseNotes(data) {
$scope.notes = data;
}
$scope.newNote = { content: '', poster: '' };
$scope.addNote = function addNote() {
Data.addNote({
content: $scope.newNote.content,
poster: $scope.newNote.post
})
.success(noteAddSuccess).error(noteAddError);
}
function noteAddSuccess(data) {
$scope.error = null;
$scope.notes.push(data);
console.log($scope.notes);
$scope.newNote = { content: '', poster: '' };
}
function noteAddError(data) {
$scope.error = data;
}
$scope.removeNote = function removeNote(id) {
if (confirm('Do you really want to remove this note?')) {
Data.removeNote(id).success(noteRemoveSuccess);
}
}
function noteRemoveSuccess(data) {
var i = $scope.notes.length;
while (i--) {
if ($scope.notes[i].id == data) {
$scope.notes.splice(i, 1);
}
}
}
});
I believe this is all the relevant code. I'm not sure why it is not displaying note.content
Thank you
Since the data update is not triggered from UI, i.e on user clicks or similar activity the scope might be unaware of the changes. In your code you are updating the data from the service, thus my first suggestion will be is to use $scope.$apply() to propagate the changes on the model to the UI.
function parseNotes(data) {
$scope.notes = data;
if (!$scope.$$phase) {
$scope.$apply();
}
}
This might help. If not then, please post back
I found my error, really simple. I was closing div tag before I was requesting {{note.content}}. It should look like:
<div class="container" ng-controller="NoteController">
<h3>Add note</h3>
<form ng-submit="addNote()">
<input type="text" ng-model="newNote.content">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<ul>
<li ng-repeat="note in notes">
#{{ note.content }}
</li>
</ul>
</div>
thank you for the replies!
I have created two directives and included them in my html. However, only the first one executes and nothing after it.
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div directive-one=""/>
<div directive-two=""/>
<div> Hello I am {{name}} and I am {{age}} years old!</div>
</div>
<script type="text/ng-template" id="myTemplate.html">
<div>Name: <input type='text' ng-model='name'/></div>
</script>
</div>
Javascript:
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope) {
$scope.name = "Jason";
$scope.age = "20";
});
app.directive('directiveOne', function () {
return {
replace: true,
template: "<div>Age: <input type = 'text' id = 'age' ng-model='age'>
</input></div>"
}
});
app.directive('directiveTwo', function () {
return {
replace: true,
templateUrl: "myTemplate.html"
}
});
Here is the fiddle: DEMO
Can't figure out what the issue is. Any help is appreciated.
You have to close your div tags with the directives in them and you don't need the ="" after either.
<div directive-one></div>
<div directive-two></div>
Here's an updated fiddle with it working.