ngModel does not work with ngView - angularjs

I want to two way bind with ng-model directive AFTER the ngview has loaded. Is this possible?
app.js
app.controller('FormController', function($scope) {
$scope.data = {
header = 'Header',
}
});
index.html
<div ng-controller="FormController">
Header: <input type="text" ng-model="data.header"> {{data.header}}
</div>
Which works fine. What I want to do is do the exact same thing after ng-view
within ng-view I would put
{{data.header}}
and it would say "Header" but does not bind the data.
Hopefully I explained the problem clearly. Any ideas?

here is a working example
In your script:
declare ngRoute as a dependency
use $routeProvider inside a config block to declare your routes
I use inline template only for simplicity (In real apps I use templateUrl)
var app = angular.module('app',['ngRoute']);
app.config(function($routeProvider){
$routeProvider.when('/',{
template: "Header: <input type='text' ng-model='data.header'> {{data.header}}",
controller: "ctrl"
});
});
app.controller('ctrl',function($scope){
$scope.data = {
header : 'Header'
};
});
In your html:
Add angular-route.js to your scripts
Add a ng-view directive

Related

ng-model not working in ui-router nested view

I have the following code structure
index.html
<body ng-app="jobPortalApp" ng-controller="mainController">
<div ui-view></div>
</body>
then following is my homepage.html template
<div id=header>
</div>
<div ui-view>
<input type="text" ng-model="test">Test</input>
<input type="submit" ng-click="signup()">
</div>
<footer>
</footer>
my angular module file is as follows
var jobPortalApp = angular.module('jobPortalApp',['ui.router']);
jobPortalApp.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider
.otherwise('/');
$stateProvider
.state('home',
{
url:'/',
templateUrl: './templates/homepage.html',
controller: 'controllerHome'
})
}).controller('mainController', function(){});
following is my home controller
jobPortalApp.controller('controllerHome',function($scope, $http) {
$scope.test="";
$scope.signup = function() {
console.log($scope.test);
}
});
Required:
I want the changed value of test in my controllerHome after the user clicks on signup
Problem:
console.log outputs blank and if I remove $scope.test="";then outputs undefined. I want the changed value of test in my controller.
You usually shouldn't bind directly to $scope due to issues with prototypal inheritance. When trying to read a value from a child scope, if the value doesn't exist you end up reading from the parent scope. But as soon as you write, you write to the child scope. Does it work if you bind to an object instead?
$scope.data = {
test: ""
};
<input type="text" ng-model="data.test">Test</input>
As an alternative, you may also want to look at the controllerAs option for your route:
controllerAs: "ctrl"
Then in your controller:
this.test = "";
And in your template:
<input type="text" ng-model="ctrl.test">Test</input>

Custom directive does not appear in the page

I have the following html page
<input type="text" value="Doe">
<h3>Search Result</h3>
<div class="list-group">
<search-result></search-result>
<search-result></search-result>
</div>
and here is my angular directive
var app=angular.module('App',['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl:'pages/main.html',
controller:'mainController'
})
})
myApp.directive("searchResult", function() {
return {
template: '<h4 class="list-group-item-heading">Doe, John</h4><p class="list-group-item-text">555 Main St., New York, NY 11111</p>'
}
});
The problem is, when I load the page the custom directive does not appear in my page. There is no error in console.I checked the inspect -> Element in the browser. It has the <search-result></search-result> but it seems that, it is ignored.
How can i fix it?
Instead of this
myApp.directive("searchResult", function()
it should be
app.directive("searchResult", function()

Angular 1.5 - Component() Method

I'm trying to get the component method working which is new for Angular 1.5. So far I acheived the following see my jsFiddle JSFIDDLE. For some reason I can not get the templateUrl working so that I can see the html template with the defined scope. Any help would be great.
JSFIDDLE
JS
var app = angular.module('myApp', []);
app.controller('mainCtrl', function($scope) {
$scope.name = "Tony Danza";
});
app.component("myBox", {
bindings: {},
controller: function($element) {
var myBox = this;
myBox.game = 'World Of warcraft';
},
controllerAs: 'myBox',
templateUrl: "/template",
transclude: true
})
HTML
<div ng-app="myApp" ng-controller="mainCtrl">
<script type="text/ng-template" id="/template">
<div style='width:40%;border:2px solid black;background-color:yellow'>
Your Favourite game is: {{myBox.game}}
</div>
</script>
Hi {{name}}
<div my-box>
</div my-box>
</div><!--end app-->
Angular components must be elements. Use <my-box> instead of <div my-box>.
The documentation on Components doesn't make this immediately clear, but it is documented.
when you want a directive that is triggered by an attribute or CSS class, rather than an element
The directive/component comparison table also explains that restrict is unavailable for components and they are always elements.

Loading a Route within a Route in Angular

I have some HTML which looks like this:
<body ng-controller="main">
<div id="main">
<div ng-view></div>
</div>
</body>
Here is the controller:
var app = angular.module('buildson', ['ngRoute', 'ngAnimate']);
app.controller('main', function($scope) {
$scope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) {
window.scrollTo(0, 0);
});
});
And here is the Routing:
//ROUTING
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'home.html'
})
.when('/courses', {
templateUrl : 'views/coursesTeaching.html'
});
});
Here is coursesTeaching.html
<div class="coursesList">
[Display a list of courses here]
Display Documentation
</div>
And here is documentationWidget.html
Documentation Content is in this file
What I want to do is when they click on this link Display Documentation It loads the documentationWidget.html content into the <div class="documentationWidget"></div> spot, I suppose it is a view within a view or a sub-route. I can't do it with jQuery Ajax or anything because I want to be able to use Angular variables inside of the loaded html file.
Take a look at ui-router as an alternative to ngRoute. This has good support for nested views amongst other things: https://github.com/angular-ui/ui-router
This has also been discussed in more detail here: Difference between ng-route & ui-router
I've been told you should use the third-party library ui-router for complex routing operations.

Very simple ng-model watch not working

Here is the jsfiddle.
http://jsfiddle.net/CLcfC/
code
var app = angular.module('app',['']);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
})
HTML
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
I am not able to see the change in $scope.text. Please help.
This is so easy but what am I missing?
Change the module creation to this, make sure you don't put a empty string in the []. (Obvious the empty string is not a module that can be injected.)
var app = angular.module('app', []);
Demo: http://jsfiddle.net/MWa66/
Your JavaScript file loads after the AngularJS initialization and that's why it fails to find your module. In order to fix it change the initialization to a manual initialization.
First change your HTML and remove the ng-app directive:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div id="appRoot">
<div ng-controller="TestCtrl">
<input type="text" ng-model='text'/>
<span>{{text}}</span>
</div>
</div>
Then go to your JavaScript and use angular.bootstrap method to manually attach your module:
var app = angular.module('app',[]);
app.controller('TestCtrl',function($scope){
$scope.text = 'Change Me';
$scope.$watch('text',function(){
alert('Changed !');
});
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('appRoot'), ['app']);
});
You can find more help on manual AngularJS initialization here.
Thank you! I solved this annoying thing!
The solution that worked for me was that I use angular UI router and there I had used the following code
.state('app.monimes', {
url: "/monimes",
views: {
'menuContent' :{
templateUrl: "templates/monimes.html",
controller: 'sampleCtrl'
}
}
})
so then in the controller I had
/***
*
*Controller for tests..
*/
.controller('sampleCtrl',['$scope','sampleService', function($scope, $sampleService) {
$scope.username="em";
// Watch for changes on the username property.
// If there is a change, run the function
$scope.$watch('username', function(newUsername) {
// uses the $http service to call the GitHub API
// //log it
$scope.log(newUsername);
// and returns the resulting promise
$sampleService.events(newUsername)
.success(function(data, status, headers) {
// the success function wraps the response in data
// so we need to call data.data to fetch the raw data
$scope.events = data.data;
});
},true);
}
]);
and in the view I had
<div>
<label for="username">Type in a GitHub username</label>
<input type="text" ng-model="username" placeholder="Enter a GitHub username, like a user" />
<pre ng-show="username">{{ events }}</pre>
</div>
but that didn't work.
so I added ng-controller="sampleCtrl"
to the div and now it works :D
so that means that the view is loaded after the controller loads and the watcher doesn't get added to the watching variable.

Resources