Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find the best way to define a model. I have set my ng-model to
model.test
and sure enough it seems to work, I did a standard
alert($scope.model.test);
Do I always have to refer to it has $scope?
So when do I need to set this up in the controller i.e.
$scope.model ={};
If I want to populate from the controller I can setup something like
$scope.model = {name: 'test', age: 56};
but what if I would like to create the model ensuring that it had only "name" and "age" set has available properties but containing NO VALUE?
Is it normal to have the model created directly on the scope? Can I not have my models created separately in a file?
As you can see I have it working, but I am not sure which way I should be going.
$scope.model = {};
$scope.model.name = ''; // default value
$scope.model.age = ''; // default value
Then you can modify it like this:
$scope.model.name = 'test';
$scope.model.age = 56;
Or add more attributes:
$scope.model.foo = 'bar';
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In angular when using resources we can bind them directly on the $scope like this:
$scope.users = Users.$query();
This could also written as:
Users.$query().$promise.then(function(users) {
$scope.users = users;
});
Have you experienced any downside of using the first approach? What are the pros and cons of each?
From angular ng-book:
$resource Instances Are Asynchronous
With all these methods, it’s important to note that when they are
invoked, the $resource object immediately returns an empty reference
to the data. This data is an empty reference, not the actual data, as
all these methods are executed asynchronously. Therefore, a call to
get an instance might look synchronous, but is actually not. In fact,
it’s simply a reference to data that Angular will fill in
automatically when it arrives back from the server.
// $scope.users will be empty
$scope.users = User.query();
We can wait for the data to come back as expected using the callback method that the methods
provide:
$scope.users(function(users) {
// logic here
});
or use raw $http from $promise attribute
$scope.users.$promise.then(function(users) {
// logic here
});
Both approaches are essentially equivalent.
The main difference between them is that in the 2nd approach, you will be able to perform certain actions once the request completes, whereas in the 1st approach, to be able to run logic when the request completes, you'll need to work with $watch statements on the users variable.
The 1st approach however, will allow you to place default values inside user which could be convenient when binding view before the request completes.
By the way, there is also a 3rd option:
$scope.users = Users.$query();
$scope.users.$promise.then(function(users) {
// perform some logic
});
This allows you to immediately bind views to the users variable in the scope, and at the same time, perform any additional logic you might need once the request completes.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Having trouble trying to recompile angular app.
Is there a way to unbootstrap after calling angular.bootstrap?
Once I do angular.bootstrap when already bootstrapped, causes errors
Thanks!
It does not seem like angular was designed to do this, and I can't think of any good reason why you would want to (but maybe you do). That said, from looking at the angular.js source code
it seems like the only way that this could work would be to remove the element you originally bootstrapped from the DOM and then re-add it and then try bootstraping again.
Here's a jsfiddle proof of concept that bootstraps a super simple app and then after 5 seconds bootstraps itself again. I'd be extremely hesitant to do something like this on a complex app but it does seem to work.
var bootstrapApp = function(appDiv) {
var isSecondTime = false;
if (appDiv) {
document.body.removeChild(appDiv);
isSecondTime = true;
}
appDiv = document.createElement('div');
appDiv.id = "myApp";
appDiv.innerHTML = (isSecondTime ? ' 2nd bootstrap': ' 1st bootstrap') + template.innerHTML;
document.body.appendChild(appDiv);
angular.bootstrap(angular.element(appDiv), ['myApp']);
return appDiv;
}
var createdAppDiv = bootstrapApp(null);
setTimeout(function() {
console.log("try boostraping again");
bootstrapApp(createdAppDiv);
}, 5000);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
As an angularJS newbie, I am puzzled by the fact I have to bind to a function returned from the service to update the view, not the data itself, I couldn't find any official document explaining this, Does anyone know why?
JSFiddle Code Sample
<div ng-controller="MyCtrl">
binding to a function works!
<p ng-bind-html-unsafe="tempLog.returnBuffer()"></p>
<br><br>
bind to the service variable: Doesn't work, why?
<p>log={{tempLog.buffer}}</p>
<br><br>
bind to scope var instead of service var, still doesn't work
<p>log={{logBuffer}}</p>
bind to a scope var which points to the service Function, works!
<p>log={{pLogFunc()}}</p>
<button ng-click="addText('more')">Trace</button><br>
</div>
JS code
var myApp = angular.module('myApp',[]);
myApp.factory('myLog', function() {
var internalBuffer = "";
return {
buffer:internalBuffer,
trace:function(input){
internalBuffer = internalBuffer + "<br>" +input;
buff = input;
},
returnBuffer:function(){
return internalBuffer;
}
}
});
function MyCtrl($scope, myLog){
$scope.tempLog = myLog;
$scope.logBuffer = myLog.buffer;
$scope.pLogFunc = myLog.returnBuffer;
myLog.trace("aaa");
$scope.addText = function(str){
myLog.trace(str)
}
}
This is not an AngularJS binding problem, this is just how javascript works.
In your service:
1 buffer is assigned to a primitive variable internalBuffer.
2 trace() accepts a parameter that changes the internalBuffer primitive
3 returnBuffer() returns the internalBuffer primitive
Since trace() changes the internalBuffer primitive, any binding to buffer does not affect the changes in the internalBuffer, furthermore, returnBuffer() returns the value of the internalBuffer so naturally the changes you made with the trace() function affects the return value of the returnBuffer() function.
Any of these suggestions may work on your end:
[1] If you want to bind from the buffer property of your myLog service, then change your trace() function to something like this:
trace:function(input){
this.buffer = this.buffer + "<br>" +input;
}
[2] You may disregard the buffer property and solely use the returnBuffer() if youdon't want to expose yourinternalBufferand only use thetrace()to have access in changing theinternalBuffer`
[3] You can use both, the buffer property provides access to another buffer format while the internalBuffer holds all the private buffers / format / or anything else that you may not want to expose to the users of the service. Just be sure to update the buffer in your trace() function by using this as well.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the best way to make use of webshims in a backbone project? Is there a way to avoid using it globally and only loading it for a specific view?
Yes this is possible. But I would always include the modernizr and polyfiller.js in the base setup.
In case you are doing this you should configure at least waitReady and basePath:
webshims.setOptions({ waitReady: false, basePath: "/js/libs/shims/" });
Your code for your view could look like this:
Backbone.View.extend({
initialize: function(){
//Load webshims
webshims.polyfill('forms forms-ext mediaelement');
},
render: function() {
this.$el.html( this.template(this.model.attributes) );
//update new created elements
this.$el.updatePolyfill();
return this;
}
});
Normally webshims delays jQuery's 'ready' event until all features are implented. In case you want to use webshims only in a specific view you can't delay it. In case you want to use the polyfilled JS/DOM API. You should wrap your JS code, which uses those APIs in a webshims.ready callback:
render: function() {
var thisObject = this;
this.$el.html( this.template(this.model.attributes) );
//update new created elements
this.$el.updatePolyfill();
//wait until video API is implemented and then use it
webshims.ready('mediaelement', function(){
$('video', thisObject.$el).play();
});
return this;
}
In case you want to speed up things, you can load it inside your view and after window.load:
$(window).on('load', function(){
//preload after onload
webshims.polyfill('forms forms-ext mediaelement');
});
This way webshims is loaded either as soon as the view starts to initialize or after onload. webshims might give you a warning in this case, that you have called it twice, but this won't hurt.
I wondered if it's possible to append a partial to the view, instead of replacing the previous one.
The usecase is as follows:
I'm building a questionaire
Upon starting the questionaire only 1 question is visible/in the DOM
The answer of question 1 dictates what question 2 should be
Upon answering question 1, question 2 gets appended to the DOM, under question 1
If question 1 is changed, all other questions are reset/removed from dom, and a fresh, unanswered question 2 appears (under 1)
Maybe using one partial a question is not the way to go, in that case please let me know what the preferred method would be (vanilla/no-angular JS?)
To give you a rough idea:
Given your app is in angularjs, you should be having all your questions inside a model in a controller:
$scope.questions = [
{
"question":"foo?",
"options":["bar1","bar2","bar3","bar4"]
"answer":2
},
{
},
{
}
];
// initially show the 1st question
$scope.currentQuestIndex = 0;
$scope.currentQuestion = $scope.questions[$scope.currentQuestIndex];
And use the currentQuestion inside your view as:
<div>Question: {{currentQuestion.question}}</div>
When the user selects a correct answer, you could simply update the current question:
$scope.submitAnswer = function(){
// check if the answer is correct
if(isCorrect){
$scope.currentQuestion = $scope.questions[$scope.currentQuestIndex + 1];
}
}
This would dynamically update your view! Thanks to the data-binding feature provided by angularjs.