I have the following:
html
<div class="panel panel-default" ng-controller="firstController">
<ul id="conversation">
<li ng-repeat="msg in messages">{{msg}}</li>
</ul>
</div>
js
var messages = [];
//Messages is updated everytime a message is sent.
var firstController = function($scope) {
$scope.messages = messages;
}
app.controller("firstController", firstController);
I have a button that updates the global javascript messages variable. I need to update the $scope messages variable everytime my button is clicked. My controller only runs when the page first loads.
How can I update $scope variables?
As it was suggested, you can use ng-click to invoke a function in the controller whenever the button is clicked. You can update the messages array within the function.
Below is a code example on how to do this. You can check this Fiddle to see it in action.
<div id="appContainer" ng-app="MyApp">
<div ng-controller="MyController">
<button ng-click="updateMessages();">Click Me</button>
<div ng-repeat="msg in messages">
<label>{{msg}}</label>
</div>
</div>
</div>
var app = angular.module('MyApp', []);
app.controller('MyController', ['$scope', function($scope) {
$scope.messages = [];
$scope.updateMessages = function() {
$scope.messages.push('Date is: ' + new Date().toString());
};
}]);
Related
HTML
chech out the below sample html, I require something like this.
<div id="parentApp" ng-app="parentApp" ng-cloak="" ng-controller="mainController">
<div id="someContent">
{{$scope.parentName}}
***some parent app actions***
</div>
<div id="childApp" ng-app="childApp">
<div id="someContent" ng-controller="secondController">
{{$scope.childName}}
***some child app actions***
</div>
</div>
</div>
Script
2 simple app and controllers for better understanding purpose.
var parentApp = angular.module('parentApp', []);
parentApp.controller('mainController', function($scope, $http) {
$scope.parentName = 'Parent!!'
});
var childApp = angular.module('childApp', []);
childApp.controller('secondController', function($scope, $http) {
$scope.childName = 'Child!!'
});
You cannot use 2 ng-app attribute on a page.
However, looking at your requirement, I think you need to use 2 controllers and do some stuff with it while maintaining the appearance of parent-child in the HTML structure. To, do that you can make use of the angular.bootstrap method.
So, you can modify the html as below:
<div id="parentApp" ng-cloak="" ng-controller="mainController">
<div id="someContent">
{{$scope.parentName}}
***some parent app actions***
</div>
<div id="childApp" ng-app="childApp">
<div id="someContent" ng-controller="secondController">
{{$scope.childName}}
***some child app actions***
</div>
</div>
</div>
And in your code, you can initialize it as below:
var parentAppDivId = document.getElementById('parentApp');
angular.bootstrap(parentAppDivId, ['parentApp']);
var parentApp = angular.module('parentApp', []);
parentApp.controller('mainController', function($scope, $http) {
$scope.parentName = 'Parent!!'
});
var childAppDivId = document.getElementById('childApp');
angular.bootstrap(childAppDivId, ['childApp']);
var childApp = angular.module('childApp', []);
childApp.controller('secondController', function($scope, $http) {
$scope.childName = 'Child!!'
});
If you already have two separate apps and are trying to leverage parts of one in another app, you can inject the module from one app into another. It's the the same structure as you've outlined above, but it will make everything from the first app available in the second app.
angular.module('childApp', ['parentApp'])...
I wish I can handle this, but in the bad way...namely I need to use $cookieStore to check either the function called or not.
Every time to use push array then I need to use $cookieStore. But it seems not practical.
Here was my DOM:
<div ng-controller="MyCtrl">
<div>
<div ng-include="'temp2.html'">
Hello, {{name}}!
</div>
</div>
</div>
<script type="text/ng-template" id="temp2.html">
<div ng-controller="MyCtrl">Another View</div>
</script>
And my angularjs controller:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
alert(1);
}
alert(1) function will be called 2 times every times the page was called.
How to avoid this problem without using watcher?
My fiddle for your convenience. Thanks!
The controller would called be twice for both the views, i would suggest you to move controller specific code to init function and use ng-init in one of your views.
var Controller = function($scope) {
$scope.init = function () {
};
};
Your View
<div ng-controller="Controller" ng-init="init()"/>
Yo don't need to specify the Controller name again in the include.... if its the same as the parent one(same as controller of main page).
just go with this
<div ng-controller="MyCtrl">
<div>
<div ng-include="'temp2.html'">
Hello, {{name}}!
</div>
</div>
</div>
<script type="text/ng-template" id="temp2.html">
<div>Another View {{name}}</div>
</script>
Js Fiddel
name will be accessible in the view you included.
Hope it will help you..
UPDATE 8:
CODE:
<% include ../partials/header %>
<script src="https://www.gstatic.com/firebasejs/3.5.2/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebase-util/0.2.5/firebase-util.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.4/angularfire.min.js"></script>
<script>
var config = {
info
};
firebase.initializeApp(config);
var fb = firebase.database().ref("posts/fun");
var app = angular.module('app', ['firebase']);
app.controller('ctrl', function ($scope, $firebaseArray, $timeout) {
$scope.data = [];
var _start = 0;
var _end = 4;
var _n = 5;
$scope.getDataset = function() {
fb.orderByChild('id').startAt(_start).endAt(_end).limitToLast(_n).on("child_added", function(dataSnapshot) {
$scope.data.push(dataSnapshot.val());
console.log("THE VALUE:"+$scope.data);
});
_start = _start + _n;
_end = _end + _n;
};
$scope.getDataset()
});
// Compile the whole <body> with the angular module named "app"
angular.bootstrap(document.body, ['app']);
</script>
<div class ="containerMarginsIndex">
<div ng-controller="ctrl">
<div class="fun" ng-repeat="d in data">
<h3 class="text-left">{{d.title}}</h3>
<div class = "postImgIndex">
<a href="details/{{d.id}}" target="_blank">
<img class= "imgIndex" ng-src="/images/uploads/{{d.image}}" >
</a>
</div>
<div class="postScore">{{d.upvotes - d.downvotes}} HP</div>
</div>
</div>
</div>
<% include ../partials/footer %>
SITUATION:
Ok, I have reworked my Firebase database architecture and changed the Firebase rules.
I am now certain the Firebase function returns a value (it is logged in the console).
But I still get the following error:
This HTML:
<div class="fun" ng-repeat="d in data">
<h3 class="text-left">{{d.title}}</h3>
<div class = "postImgIndex">
<a href="details/{{d.id}}" target="_blank">
<img class= "imgIndex" ng-src="/images/uploads/{{d.image}}" >
</a>
</div>
<div class="postScore">{{d.upvotes - d.downvotes}} HP</div>
</div>
gets REPLACED by this once RENDERED:
<!-- ngRepeat: d in data --> == $0
What have I done wrong ?
It's not displaying in your view because you have nothing on the $scope and you're not using {{}} to interpolate your data. See the following changes:
Assign data to a $scope variable to be used in the view:
$scope.data = [];
var _start = 0;
var _end = 4;
var _n = 5;
var getDataset = function() {
fb.orderByChild('time').startAt(_start).endAt(_end).limitToLast(_n).on("child_added", function(dataSnapshot) {
$scope.data.push(dataSnapshot.val());
});
_start = _start + _n;
_end = _end + _n;
And your view, use ngRepeat and {{}} to interpolate:
<div class ="containerMarginsIndex">
<div class="fun" ng-repeat="d in data">
<h3 class="text-left">{{d.title}}</h3>
<div class = "postImgIndex">
<a href="details/{{post.id}}" target="_blank">
<img class= "imgIndex" src="/images/uploads/{{post.image}}" >
</a>
</div>
<div class="postScore">({{d.upvotes - d.downvotes}}) HP</div>
</div>
</div>
Add your scroll listener within your controller. The function more does not exist indeed, however you do have a $scope.more method.
app.controller('ctrl', function ($scope, $firebaseArray, $timeout) {
// ORDERED BY TIME:
var ref = firebase.database().ref("posts/fun");
var scrollRef = new Firebase.util.Scroll(ref, "time");
$scope.posts = $firebaseArray(scrollRef);
scrollRef.scroll.next(5);
// AS DATA APPEARS IN DATABASE ORDERED BY TIME:
ref.once('value', function(snap) {
$scope.rawdata = snap.val();
$scope.$apply();
});
$scope.more = function() {
scrollRef.scroll.next(5);
};
// Add scroll listener
window.addEventListener('scroll', function() {
if (window.scrollY === document.body.scrollHeight - window.innerHeight) {
$scope.$apply($scope.more);
}
});
});
Note that I am calling $scope.more within $scope.$apply so that the scope is digested at the end of the call. Indeed a JS listener on a window scroll event is out of the Angular lifecycle so we need to manually $digest the scope for Angular to update all its watchers and update the HTML. Search online about $scope.$apply if you want to learn more about it.
About your first problem
Your angular application is not started because angular is never initialized. For that you need either to load it synchronously and use the ng-app directive, or if you don't want to change anything with your code you can simply add these lines after your module and controller definition:
// Compile the whole <body> with the angular module named "app"
angular.bootstrap(document.body, ['app']);
You need to include $scope.$apply() because the the scroll event executes outside Angular's context.
Also the event listener should be inside your controller so that the scoped more function is accessible.
Here's an updated fiddle:
https://jsfiddle.net/xue8odfc/2/
I'd say the problem with Angular not resolving the {{post.image}} etc. is due to incompatibilities among the libraries you are referencing. I suggest testing using the versions from the working jsfiddle:
<script src="https://cdn.firebase.com/js/client/2.0.3/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebase-util/0.2.5/firebase-util.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.1/angular.min.js"></script>
<script src="https://cdn.firebase.com/libs/angularfire/1.1.4/angularfire.min.js"></script>
I'm using Angular Bootstrap UI and I have a working tooltip.
HTML:
<div ng-app="helloApp">
<div ng-controller="helloCtrl as hello">
<a tooltip-trigger="click" tooltip-placement="bottom" uib-tooltip-html="<h1 ng-click='hello.clickInsideToSeeTheWorld()'>Click again!</h1>">Click me to see the tooltip</a>
</div>
</div>
Javascript:
angular.module('helloApp', ['ui.bootstrap'])
.controller('helloCtrl', helloCtrl)
function helloCtrl() {
var vm = this;
vm.clickInsideToSeeTheWorld = function() {alert(123)}
}
When I open up the tooltip, ng-click doesn't work. No alert appears. I receive no errors in my console. This is because the HTML isn't compiled. How can I properly compile the tooltip html to get this to work?
Extending the previous answer: You can probably use
uib-tooltip-template
instead of
uib-tooltip-html
when you exploit the angular template cache.
I understand that you maybe do not want to create an external template.html, but you do not have to do so. Simply try:
var app = angular.module("test", ['ui.bootstrap']);
app.controller("testController", function($scope, $templateCache) {
$scope.clickInsideToSeeTheWorld = function() {
alert(123)
}
if (!$templateCache.get ('template.html')) {
$templateCache.put (
'template.html',
'<a ng-click="clickInsideToSeeTheWorld()">Click again!</a>'
);
}
});
and
<div ng-app="test" ng-controller="testController">
<p style="margin-top: 5em;" uib-tooltip-template="'template.html'" tooltip-popup-close-delay="3000" >
Click me to see the tooltip
</p>
Here's an external plunker as well:
https://plnkr.co/edit/Dsi69MQg4NfgOSI5ClFh?p=preview
I added uib-tooltip-template instead uib-tooltip-html and changed this to $scope.
index.html
<body>
<script>
var app = angular.module("test", ['ui.bootstrap']);
app.controller("testController", function($scope) {
$scope.clickInsideToSeeTheWorld = function() {
alert(123)}
});
</script>
<div ng-app="test" ng-controller="testController">
<p style="margin-top: 5em;" uib-tooltip-template="'template.html'" tooltip-popup-close-delay="3000" >
Click me to see the tooltip
</p>
</div>
</body>
template.html
<a ng-click="clickInsideToSeeTheWorld()">Click again!</a>
Here is working Plunker
Or Alternative solution is for you to compile code yourself and then assign it to tooltip html
var sc = scope.$new( true ); //scope for html
sc.hello = {} // assign your hallo object to new scope
var compiledHtml = $compile( '<h1 ng-click="hello.clickInsideToSeeTheWorld()">Click again!</h1>')( sc );
Then you can set tooltip html to compiledHtml.
Consider two div areas as follows, in html file
<div class="divArea1" ng-controller="myController">
<input ng-click="updateName()" type="button" value="button"/>
</div>
<div class="divArea1" ng-controller="myController">
<p>{{name}}</p>
</div>
Following is the angular js example
productApp.controller("myController", [ '$scope', function($scope) {
$scope.name= "XYZ";
$scope.updateName= function() {
$scope.name = "ABC";
};
} ]);
problem is when I am trying to update the name, upon click on update button it is not visible in the second in the div area. Is there any mistake i am doing.
What you have is two different controllers (with two separate scopes) with the same name.
You need to put the controller in the parent controller to keep the name in the same scope as the button:
<div id="container" ng-controller="myController">
<div class="divArea1">
<input ng-click="updateName()" type="button" value="button"/>
</div>
<div class="divArea1">
<p>{{name}}</p>
</div>
</div>
Controllers are not singletons. Each time you have a new controller, you're having a new instance of this controller, with a new isolated scope.
If your need is to share data between controllers, you should use a factory (which is a singleton).
angular.module('app').factory('mySharedData', function(){
var service = {
object : objectToShare
};
var objectToShare = {};
return service;
});
And from your controller :
angular.module('app').controller('myController',
['$scope','mySharedData',
function($scope, mySharedData){
$scope.someObject = mySharedData.object;
$scope.updateName= function() {
$scope.someObject.name = "ABC";
};
}
]);
And from your view :
<div class="divArea1" ng-controller="myController">
<input ng-click="updateName()" type="button" value="button"/>
</div>
<div class="divArea1" ng-controller="myController">
<p>{{someObject.name}}</p>
</div>
Note : I've encapsulated the name property into an object because objects are passed by reference, and strings by value. This allows you to make it easier to share your values and to have it automatically updated into the service and other controllers, without having to access your property through accessors.
here is demo http://jsfiddle.net/wg7pb1yu/3/
inject $rootScope so that it will do from global scope
productApp.controller("myController", [ '$scope','$rootScope', function($scope, $rootScope) {
$rootScope.name= "XYZ";
$scope.updateName= function() {
$rootScope.name = "ABC";
};} ]);
Hope this will help you