This code works:
<div ng-include src="'Test.html'"></div>
This code doesn't:
<div ng-include src="ctrl.URL"></div>
(ctrl.URL is set to "Test.html"). I also set it to 'Test.html' and "'Test.html'" with the same results.
How can I successfully convert this into an expression for use in ng-include src? I think I am missing some knowledge on how strings get parsed but I was pretty sure 'Test.html' should work.
I found that I am too incompetent to rename my own variables. ctrl.URL was really ctrl.URl. Now everything is working.
Check this, maybe this fiddle will help you.
HTML and templates:
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url" onload='myFunction()'></div>
</div>
<!-- template1.html -->
<script type="text/ng-template" id="template1.html">
Content of template1.html
</script>
<!-- template2.html -->
<script type="text/ng-template" id="template2.html">
<p ng-class="color">Content of template2.html</p>
</script>
The controller:
function Ctrl($scope) {
$scope.templates = [{
name: 'template1.html',
url: 'template1.html'},
{
name: 'template2.html',
url: 'template2.html'}];
$scope.template = $scope.templates[0];
$scope.myFunction = function() {
$scope.color = 'red';
}
}
Related
I am new in angular js, I am trying to format a json data with angular js.
Here is my json data
[
{"field_add_link": "Home"},
{"field_add_link": "About Us"}
]
here is my conroller
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('myController',function($scope, $http) {
$http.get('http://localhost/drupal3/menu')
.then(function(response) {
$scope.links = response;
});
});
and finally here is how i am fetching the json data with angular
<div class="col-md-8 content" ng-controller ="myController">
<div class="col-md-12" ng-repeat="link in links" ng-bind-html="links">
<p>{{ link.field_add_link }}</p>
</div>
</div>
no output was shown after this, giving an error Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context. in the browser's console
but when I used ng-bind-html="links[0].field_add_link instead of ng-bind-html="links" and <p>{{ link[0].field_add_link }}</p> instead of <p>{{ link.field_add_link }}</p>
then i get Home as output 'without interpreting the tag'
Pls, how do I go about this?
First of all you dont need the ng-bind-html attribute on your div with ng-repeat. It should be on your p tag. Second, you need to bind link (the current element of the ng-repeat-loop) not links (the array). Although you need to look into the error [$sce:unsafe]. HTMl can only be bind to an element-body if it is trusted. For that you need to have, for example, a filter.
myApp.filter ('to_trusted', ['$sce', function ($sce) {
return function (text) {
return $sce.trustAsHtml (text);
};
}]);
<div class="col-md-8 content" ng-controller ="myController">
<div class="col-md-12" ng-repeat="link in links">
<p ng-bind-html="link.field_add_link | to_trusted"></p>
</div>
</div>
You just need to move your ng-bind-html from div to <p> like following code.
<p ng-bind-html="link.field_add_link"></p>
var myApp = angular.module('myApp', ['ngSanitize']);
myApp.controller('myController', function($scope, $http) {
var data = [{"field_add_link": "Home"},
{"field_add_link": "About Us"}];
$scope.links = data;
//For demo, removed the http call
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular-sanitize.js"></script>
</head>
<body ng-app="myApp">
<div class="col-md-8 content" ng-controller="myController">
<div class="col-md-12" ng-repeat="link in links">
<p ng-bind-html="link.field_add_link"></p>
</div>
</div>
</body>
I've got a page in my website in which I want to show a checkbox. I only want to show the checkbox if the model is initially false. So I wrote this (this was my initial code, but it was a simplified version of what I have myself. I updated the code in the snippet at the end of this question to show the problem):
<div ng-if="!the_field">
<input ng-model="the_field" type="checkbox">
</div>
The problem is that if I click the checkbox, it disappears. That of course makes sense, but I have no idea how to solve this.
So what I basically want is to show the checkbox if the model was false upon rendering the HTML. But after that I want to somehow break the databinding so that the checkbox remains on the page even if the model changes to true.
Does anybody know how I can achieve this? All tips are welcome!
[EDIT]
I would prefer doing this from within the template, so that I don't get a double list of these fields (because I've got about 50 of them). Any ideas?
[EDIT 2]
Turns out that it did work with the example above, which was a simplified version of my own code. In my own code however, I'm not using simple a field, but an item in a dict. I updated the code above and made a snippet below to show the problem:
var MainController = function($scope){
$scope.the_field = {};
$scope.the_field.item = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{the_field.item}}
<div ng-if="!the_field.item">
child: {{the_field.item}}<br>
<input ng-model="the_field.item" type="checkbox">
</div>
</div>
You can clone the source object. Like this:
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.the_field = false;
$scope.the_field_clone = angular.copy($scope.the_field);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{the_field}}
<div ng-if="!the_field_clone">
<input ng-model="$parent.the_field" type="checkbox">
</div>
</div>
http://jsbin.com/ditoka/edit?html,js
Update - option 2 - Directive
angular.module('app', []).
controller('ctrl', function($scope) {
$scope.the_field = false;
}).
directive('customIf', function() {
return {
scope: {
customIf: '='
},
link: function(scope, element, attrs) {
if (!scope.customIf) {
element.remove();
}
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
{{the_field}}
<div custom-if="!the_field">
<input ng-model="the_field" type="checkbox">
</div>
</div>
It works with the code of your question, try it out ;)
(see What are Scopes?)
var MainController = function($scope){
$scope.the_field = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{the_field}}
<div ng-if="!the_field">
child: {{the_field}}<br>
<input ng-model="the_field" type="checkbox">
</div>
</div>
The answer to your updated question:
You can use another property in your model, edited when the first click occurs...
var MainController = function($scope){
$scope.model = {init: true, the_field: false};
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-controller="MainController">
parent: {{model.the_field}}
<div ng-if="!model.the_field || !model.init">
<input ng-model="model.the_field" type="checkbox" ng-click="model.init=false;">
</div>
</div>
I am new to Angular. I went to intro-tutorials on some website.
There I learned that I can access controller functions and controller-local variables using controller-name and without $scope service. Like for example:
<div ng-controller="someController">
someController.someFunction()
someController.someVariable
</div>
I my simple application I have written a controller in controllers.js and using it in home.html. I have defined the mapping in app.js
I provided a button tag for it in html but the controller function is just not responding.
Looking at my js and HTML page you will know what I am trying to accomplish.
Here' controllers.js:
app.controller('welcomeStoryPublishCtrl', ['$log','$http',function($log,$http){
this.wsPublish = {};
this.publishGroup = function(wsPublish){
console.log('here');
$http({
method:'POST',
url: 'http://localhost:9090/Writer/publishStory',
header: {'Content-Type':'application/json'},
data: wsPublish
});
};
this.public = function(){
console.log('from public');
};
}]);
home.html
<html>
<head>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js" ></script>
<script src="https://jspm.io/system#0.16.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
</head>
<body>
<div>
<div id="welcomeStory">
<span id="wsTitleBub">Title</span>
<input id="wsTitle" type="text" ng-model="wsPublish.welcomeStoryTitle" />{{wsPublish.welcomeStoryTitle}}
<h6>Words..</h6>
<textarea id="wsWords" ng-model="wsPublish.welcomeStoryWords"></textarea>
<input id="wsPublish" type="button" name="wsPublish" value="Publish" ng-click="pub = !pub" />
<input id="wsAddShelf" type="button" name="wsAddToShelf" value="Add To Shelf" ng-click="addToShelf()" />
</div>
<div id="wsPublishTo" ng-show="pub">
<ul>
<li>
<input type=submit id="wsgroups" value="Group" ng-click="publishGroup(wsPublish)" />
</li>
<li>
<button id="wsPublic" ng-click="public()">Public</button>
</li>
</ul>
</div>
</div>
</body>
</html>
I know that I can do this by injecting $scope module dependency and I know controller instantiation always creates a $scope object itself.
But what if try doing so like this? What am I doing wrong here?
And here is app.js:
angular.module('Writer', ['AllControllers','ngRoute'])
.config(['$routeProvider', function($routeProvider,$Log){
$routeProvider.when('/Diary',{
templateUrl:'pages/login.html',
controller: 'LoginFormController'
})
.when('/loginPg',{
template: 'Hello from app.js'
})
.when('/home',{
templateUrl: './pages/home.html',
controller: 'welcomeStoryPublishCtrl'
})
.otherwise({redirectTo : '/Diary'});
}]);
First off all your input elements are not wrapped in a <form> tag and this is why your button should not be working properly. If you insist to use <button> it should be in a <form> tag so it "submits" the form, if not, go with <input type="submit"..>
Lastly, i would suggest you to use services for your http requests as this is a common good practice. :)
In your HTML you have not mentioned the ng-app directive neither have you mentioned your controller directive ng-controller.
Your HTML
<body ng-app="someApp">
<div>
<div id="welcomeStory" ng-controller="welcomeStoryPublishCtrl as wsCtrl">
<!-- Rest of your code -->
<button ng-click="wsCtrl.public()">Public</button>
Your JS
var app = angular.module('someApp', []);
app.controller('welcomeStoryPublishCtrl', ['$log','$http',function($log,$http){
this.wsPublish = {};
this.publishGroup = function(wsPublish){
console.log('here');
$http({
method:'POST',
url: 'http://localhost:9090/Writer/publishStory',
header: {'Content-Type':'application/json'},
data: wsPublish
}).success(function(data){
console.log('run success!');
});
};
this.public = function(){
console.log('from public');
};
}]);
Hope this helps.
Are you missing ng-app attribute ?
I currently have this site - http://dev.5874.co.uk/scd-data/ where I have a dropdown which displays results from WP-API which I am pulling in through AngularJS.
It currently combines the two sets of results as they're separate URL's, the results are in categories within a custom post type so if both posts are 'tagged' in the same category chosen they display twice. I need a way to combine the two sets of results but only showing one of the posts - I hope this makes sense. I'm very new to API data and AngularJS and I imagine there is a much simpler way of doing this. Any help would be much appreciated. Here is a snippet of my code to show how it's currently working.
Thanks in advance!
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<style>
.desc {display: none;}
</style>
<script type="text/javascript">
$(function(){
$('.selectOption').change(function(){
var selected = $(this).find(':selected').text();
//alert(selected);
$(".desc").hide();
$('#' + selected).show();
}).change()
});
</script>
<script>
var app = angular.module('myApp', []);
app.controller('northWestCtrl', function($scope, $http) {
var url = 'http://scd.blaze.wpengine.com/wp-json/posts?type=listings&filter[listing_area]=northwest';
$http.get(url).then(function(data) {
$scope.data = data.data;
});
});
</script>
<select class="selectOption">
<option>Search by Region</option>
<option>NorthWest</option>
<option>NorthEast</option>
<option>Midlands</option>
<option>EastAnglia</option>
<option>SouthEast</option>
<option>SouthWest</option>
<option>Scotland</option>
<option>Wales</option>
<option>NorthernIreland</option>
<option>ChannelIslands</option>
</select>
<div id="changingArea">
<body ng-app="myApp">
<div id="NorthWest" class="desc">
<div ng-controller="northWestCtrl">
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<img src="{{d.acf.logo}}">
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
</div>
</div>
</body>
</div>
Here is a working code pen - http://codepen.io/anon/pen/yePYdq
Angular is a great JavaScript front-end framework to choose, and you're off to a good start, but a lot of changes could be made. I've made some suggested changes for easier ways to do things below.
See this CodePen for all changes.
It looks like you've grasped the idea of ng-repeat, but there's definitely a lot of repeated HTML and JS in your view and controller, so let's see if we can do better.
Let's try this without jQuery to avoid direct manipulation of the DOM. And instead of many controllers, we can do this with a single controller.
<div ng-app="MyApp">
<div ng-controller="MyController">
...
</div>
</div>
<script type="text/javascript">
var app = angular.module('MyApp', []);
app.controller('MyController', ...);
</script>
For the dropdown, we'll use ng-repeat in our view and display the names of the shooting types from our model
...
<select ng-model="selectedListing">
<option
ng-repeat="listingShootingType in listingShootingTypes"
value="{{listingShootingType.name}}">
{{listingShootingType.name}}
</option>
</select>
...
<script type="text/javascript">
...
// Our selections/filters
$scope.listingShootingTypes = [
'All',
'Air Rifle/Air Pistol',
'Clay',
'ABT',
'Double Trap',
'English Skeet',
'English Sporting',
'Fitasc',
'Olympic Skeet',
'Olympic Trap',
'Simulated Game',
'Sport Trap/Compact',
'Universal Trench',
'ZZ/Helice',
'Rifle',
'Centrefire Target Rifle',
'Gallery Rifle',
'Muzzle Loading',
'Practice Shotgun',
'Smallbore Rifle'
];
...
</script>
With only one controller, we can still use ng-repeat for each listing.
<div ng-repeat="d in data">
<h2 class="entry-title title-post">{{d.title}}</h2>
<div id="listing-image"><img src="{{d.acf.logo}}"></div>
<div id="listing-contact">Contact: {{d.acf.contact}}, {{d.acf.position}}</div>
<div id="listing-address-1">
{{d.acf.address_1}}, {{d.acf.address_2}} {{d.acf.address_3}} {{d.acf.town}} {{d.acf.county}} {{d.acf.postcode}}
</div>
<div id="listing-phone">Telephone: {{d.acf.telephone}}</div>
<div id="listing-mobile">Mobile: {{d.acf.mobile}}</div>
<div id="listing-email">Email: {{d.acf.email}}</div>
<div id="listing-website">Website: {{d.acf.website}}</div>
<div id="listing-established">Established: {{d.acf.established}}</div>
<div id="listing-about">About: {{d.acf.about}}</div>
<div id="listing-mailingaddress">Mailing Address: {{d.acf.mailing_address_}}, {{d.acf.mailing_address_2}}, {{d.acf.mailing_address_3}}, {{d.acf.mailing_town}}, {{d.acf.mailing_county}}, {{d.acf.mailing_postcode}}</div>
<div id="listing-directions">Directions: {{d.acf.directions}}</div>
<div id="scd-link">View on The Shooting Club Directory</div>
</div>
Finally... How do we only display listings that match our selected shooting type from the dropdown? We could use a custom Angular filter!
...
<div ng-repeat="d in data | filter:isSelectedListing">
...
<script type="text/javascript">
...
// Let's define a custom Angular filter because the WordPress JSON is complex
$scope.isSelectedListing = function(listing) {
// Show nothing if nothing is selected
if (angular.isUndefined($scope.selectedListing) || $scope.selectedListing == '') {
return false;
}
// Show all if 'All' is selected
if ($scope.selectedListing == 'All') {
return true;
}
// If the shooting type we're looking for is present, show the listing.
// To do this, we parse the WordPress JSON object model.
if (angular.isDefined(listing.terms.listing_shooting_type)) {
for (var i = 0; i < listing.terms.listing_shooting_type.length; i++) {
if (listing.terms.listing_shooting_type[i].name == $scope.selectedListing) {
return true;
}
}
}
return false;
};
...
</script>
Hopefully this gives you an idea of how we better leverage ng-repeat + DRY :)
The entire CodePen is here.
I am building a quick Angular app that uses a service to grab a JSON from a URL.
The JSON structure looks like this:
{news:[{title:"title",description:'decription'},
{title:"title",description:'decription'},
{title:"title",description:'decription'}
]};
What I need is just the array within the news object.
My code to import the JSON is as follows:
app.factory('getNews', ['$http', function($http) {
return $http.get('URL')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
Then to add the data to the $scope object in the controller I do this:
app.controller('MainController', ['$scope','getNews', function($scope, getNews) {
getNews.success(function(data)) {
$scope.newsInfo = data.news;
});
});
But it doesn't work. When I load the html page, there is only white. My thinking is that this is because it isn't grabbing the array within the JSON and using that data to populate the HTML directive I set up.
newsInfo.js:
app.directive('newsInfo',function(){
return {
restrict: 'E',
scope: {
info: '='
},
templateUrl:'newsInfo.html'
};
});
newsInfo.html:
<h2>{{ info.title }}</h2>
<p>{{ info.published }}</p>
My HTML doc is:
<head>
<title></title>
<!--src for AngularJS library-->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
</head>
<body ng-app="THE APP NAME"> <!--insert ng app here-->
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
<!-- Modules -->
<script src="app.js"></script>
<!-- Controllers -->
<script src="MainController.js"></script>
<!-- Services -->
<script src="getNews.js"></script>
<!-- Directives -->
<script src="newsInfo.js"></script>
</body>
Thoughts?
Change
<newsInfo info="news"></newsInfo>
to
<news-info info="news"></news-info>
example: https://jsfiddle.net/bhv0zvhw/3/
You haven't specified the controller.
<div ng-controller="MainController"> <!--insert ng controller here-->
<div ng-repeat="news in newsInfo"><!--insert ng repeat here-->
<!-- directive goes here-->
<newsInfo info="news"></newsInfo>
</div>
</div>
$scope.getNews = function(){
return $http.get('URL').success(function(data) {
return data.news;
})
};
^ This, just change it so that the success function returns only the news!
While I am answering my own question, I should point out that everyone's answers were also correct. The code had multiple errors, but the final error was fixed by doing the following:
Apparently I had to upload the newsInfo.html doc to an S3 bucket and use that URL as “Cross origin requests are only supported for HTTP.” But then Angular blocked that external source with the Error: "$sce:insecurl Processing of a Resource from Untrusted Source Blocked".
So since the html template was so simple, i just bipassed this issue by typing in the template directly into the .js directive and it worked! thanks everyone for the help!