Variable doesn't change value in angular controller - javascript

I have html page with
<div ng-controller="MyCtrl">
<div ng-view>Some content</div>
myVar: {{myVar}}
</div>
And angular controller:
myModule.controller('MyCtrl', function($scope, $location) {
$scope.myVar = false;
$scope.someAction = function() {
$location.path('/anotherPath');
$scope.myVar = true; // changes in controller, but not in view
}
});
My module is
var myModule = angular.module('myModule', ['ngRoute']).config(function ($routeProvider) {
$routeProvider
.when('/anotherPath', {
templateUrl: 'anotherPath.html',
controller: 'MyCtrl'
})
.otherwise({
redirectTo: '/anotherPath.html'
})
});
anotherPath.htmlcontains only
<input data-ng-click="someAction()" type="button" class="btn" value="Some action">
After clicking on this input controller changes path, but in view value of myVar is still false. Why?

Here, you have defined your controller twice. Once on the parent div:
<div ng-controller="MyCtrl">
And once on the route for /anotherPath:
$routeProvider
.when('/anotherPath', {
templateUrl: 'anotherPath.html',
controller: 'MyCtrl' <-- This will be assigned to <div ng-view>
})
Leaving you with something like:
<div ng-controller="MyCtrl">
<div ng-view ng-controller="MyCtrl">
</div>
</div>
Therefore, when you call $scope.someAction() you are calling the function defined on the controller assigned to your inner view, rather than the function defined on the parent controller.
You should give your View its own unique controller in the route definition:
Angular:
$routeProvider
.when('/anotherPath', {
templateUrl: 'anotherPath.html',
controller: function($scope) {
// You don't necessarily need an implementation here
}
})
HTML:
<div ng-controller="MyCtrl">
<div ng-view>Some content</div>
myVar: {{myVar}}
</div>

Related

JQuery selector not working in AngularJS controller

I have a viewA and corresponding ControllerA but on click of an image on viewA i have to navigate to another ViewB and corresponding ControllerB, in ViewB have some check boxes then have a button on viewB that takes us to ViewA, then again i want to click the image on ViewA and Navigate to ViewB and restore the checkBox values (Checked, Unchecked). I have stored the values of checkboxes to service variable.
<body ng-app='demo'>
<script type="text/ng-template" id="home.html">
<h1> viewA </h1>
<img src="src" />
</script>
<script type="text/ng-template" id="about.html">
<h1> viewB </h1>
<h4>Click me to see ViewA: <input id="myCheckBox" type="checkbox" ng-model="checked" ng-change='checkView()'></h4>
</script>
<div>
<div ng-view></div>
</div>
</body>
script:
var demo = angular.module('demo', []);
demo.controller('HomeController', function ($scope) {});
demo.controller('AboutController', function ($scope,$location) {
$scope.checkView=function(){
//if($scope.checked)
if($('#myCheckBox').prop('checked') == true)
$location.url('/home');
}
});
demo.config(function ($routeProvider) {
$routeProvider.
when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
}).
when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
}).
otherwise({
redirectTo: '/home'
});
});
TRY THIS CODE:

Problems with implementing separate controller for each md-tab

My template HTML file 'testview.html' looks like this:
<div class="container-fluid">
<md-toolbar>
<h2 class="md-toolbar-tools">
<span>Test View</span>
</h2>
</md-toolbar>
<md-tabs md-stretch-tabs
md-selected="selectedIndex">
<md-tab label="basicConfig">
</md-tab>
<md-tab label="awardSettings">
</md-tab>
</md-tabs>
<div id="content" ui-view flex> </div>
</div>
This is my route controller 'testview.js':
angular
.module('app.testview')
.controller('TestView', TestView)
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('basicConfig', {
url: '/basicConfig',
templateUrl: 'app/testview/testview_partials/basicConfig.html',
controller: 'BasicConfig as vm'
})
.state('awardSettings', {
url: '/awardSettings',
templateUrl: 'app/testview/testview_partials/awardSettings.html',
controller: 'AwardSettings as vm'
})
}]);
TestView.$inject = ['$state', '$scope', '$location'];
function TestView(state, $scope, $location) {
$scope.selectedIndex = -1;
$scope.$watch('selectedIndex', function(current, old) {
switch (current) {
case 0:
$location.url("/basicConfig");
break;
case 1:
$location.url("/awardSettings");
break;
}
});
}
Here's what my awardSettings.html looks like:
<form name="awardSettingsForm" id="awardSettingsForm">
<md-content flex layout-padding layout="row" layout-sm="column" layout-align-sm="space-between start" layout-align="space-between center">
<label style="font-size: 24px;">Award Settings</label>
</md-content>
</form>
I have my basicConfig & awardSettings html & controllers defined in separate files. I know that my routes are working correctly. But my problem is that I want the contents of basicConfig.html & awardSettings.html within their tabs. But that's not working. IT looks like below when I click on the tab
Any help would be appreciated. Thanks!
Never mind. I figured out what I was doing wrong. Had to change sub states to be part of the main state ie. change state from 'basicConfig' to 'testview.basicConfig'.
function stateConfig ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('testview.basicConfig', {
templateURL: 'app/testview/testview_partials/basicConfig.html',
controller: 'BasicConfig'
})
.state('testview.awardSettings', {
template: '<h3>Award!!</h3>',
controller: 'AwardSettings'
})
}

Angular routes giving 404 error

I'm getting 404 errors when I try to click through my angular routes, and I'm not sure whats wrong. I have these links:
Home
Portfolio
About
Travel
And the routes are set up here in routes.js
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'mainController'
})
.when('/portfolio', {
templateUrl: 'portfolio.html',
controller: 'mainController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'mainController'
})
.when('/travel', {
templateUrl: 'travels.html',
controller: 'mainController'
});
});
My understanding is that when I click on the , for instance, the controller will look for /about in the routes provider. Then it will see that the template about.html fills that request, and then about.html will fill into ng-view. The request is just giving me a 404 at http://localhost:8000/about, though. What am I doing wrong?
Getting no errors, but here's the rest of my angular app for reference:
var app = angular.module('app', ['ngRoute']);
app.controller('mainController', ['$scope', '$routeParams', function($scope, $routeParams) { }]);
And the HTML
<div class="mountainSection">
<div class="ang-wrap" ng-view></div>
</div>
<div class="controlPanel">
<div class="buttonWrap">
<div class="home button">
Home
</div>
<div class="divider">|</div>
<div class="portfolio button">
Portfolio
</div>
<div class="divider">|</div>
<div class="about button">
About
</div>
<div class="divider">|</div>
<div class="intl button">
Travel
</div>
</div>
</div>

Background image not showing up in AngularJS

My custom background image is not showing up in AngularJS. Can't figure out why.
When I test $scope.setBackground in console, I get Object {background-image: "url(image.jpg)"}
Controller:
app.controller('backgroundImageCtrl', function($scope, $http) {
$scope.setBackground = {
'background-image' : 'url(image.jpg)'
};
})
HTML:
<script type = "text/ng-template" id="/page.html" ng-controller="backgroundImageCtrl" ng-style="setBackground">
<div>
...
</div>
</script>
var app = angular.module('myApp', []);
app.controller("myCtrl", function ($scope) {
$scope.style= {};
$scope.setBackground = function (date) {
$scope.style = {
'background-image': 'url("https://www.gravatar.com/avatar/10821c595d354140ee66f2a04fb11b7c?s=32&d=identicon&r=PG&f=1")'
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<button ng-click="setBackground()">set background</button>
<div ng-style="style">see the background</div>
</div>
</div>
Simple solution as suggested by #Mosh Feu, simply place ng-controller="backgroundImageCtrl" and ng-style="setBackground" in an inner div
<script type = "text/ng-template" id="/page.html">
<div ng-controller="backgroundImageCtrl" ng-style="setBackground">
...
</div>
</script>
you should use setBackground in div that use your template. try like this.
<div ng-include src="/page.html" ng-style="setBackground"></div>
var mainApp = angular.module("mainApp", ['ngRoute']);
mainApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/addStudent', {
templateUrl: 'addStudent.htm',
controller: 'AddStudentController'
}).
when('/viewStudents', {
templateUrl: 'viewStudents.htm',
controller: 'ViewStudentsController'
}).
otherwise({
redirectTo: '/addStudent'
});
}]);
mainApp.controller('AddStudentController', function($scope) {
$scope.message = "This page will be used to display add student form";
$scope.setBackground = {
'background-image' : 'url(https://www.gravatar.com/avatar/10821c595d354140ee66f2a04fb11b7c?s=32&d=identicon&r=PG&f=1)'
};
});
mainApp.controller('ViewStudentsController', function($scope) {
$scope.message = "This page will be used to display all the students";
$scope.setBackground = {
'background-image' : 'url(https://www.gravatar.com/avatar/6755dcaf172d19cb9976bedcc56cfed3?s=48&d=identicon&r=PG&f=1)'
};
});
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
<div ng-app = "mainApp">
<p>Add Student</p>
<p>View Students</p>
<div ng-view ng-style="setBackground"></div>
<script type="text/ng-template" id="addStudent.htm">
<h2> Add Student </h2>
{{message}}
</script>
<script type = "text/ng-template" id="viewStudents.htm">
<h2> View Students </h2>
{{message}}
</script>
</div>

ng-repeat throwing invalid Expression

I'm a total angular noob and trying to create a simple test app where. I'd like to read out some userdata in a partial. The user data is in my event controller. I assign the event controller to a form in my new.html partial after navigating to #/new via a route controller.
The error I get when trying to loop through the users in my partial is "Error: ngRepeat:iexp Invalid Expression". I can't figure out how to ng-repeat through those users.
Any thoughts?
My index.html:
<div class="container" style="width: 500px; margin: 0 auto;">
<ul class="nav nav-pills" ng-controller="NavigationController as navigationCtrl">
<li ng-class="{active: navigationCtrl.isActive(1)}">
Home
</li>
<li ng-class="{active: navigationCtrl.isActive(2)}">
Nieuw
</li>
<li ng-class="{active: navigationCtrl.isActive(3)}">
Nog een
</li>
</ul>
<div ng-view></div>
</div>
My new.html partial
<form action="" ng-controller="EventController as event">
<div ng-repeat="users as user">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="user.name">
<br>
<label>Emailaddress</label>
<input type="email" class="form-control" name="email" ng-model="user.email">
<br>
<input class="btn btn-default" type="submit" ng-click="event.addEvent($event)" value="Klik">
</div>
</form>
And last: My angular code
(function () {
var app = angular.module('testApp', ['ngRoute']);
app.controller('NavigationController', ['$scope', '$route', function ($scope, $route) {
$scope.$route = $route;
this.activeTab = 1;
this.setActiveTab = function (tab) {
this.activeTab = tab;
};
this.isActive = function (tab) {
if ($route.current && $route.current.activeTab) {
return $route.current.activeTab === tab;
}
return false;
};
}]);
app.controller('EventController', ['$scope', '$controller', function ($scope, $controller) {
this.users = [
{name: 'aa'},
{name: 'bb'}
];
this.addEvent = function (e) {
e.preventDefault();
console.log(this);
};
}]);
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/new', {
templateUrl: 'partials/new.html',
controller: 'NavigationController',
activeTab: 2
}).
when('/another', {
templateUrl: 'partials/another.html',
controller: 'NavigationController',
activeTab: 3
}).
otherwise({
redirectTo: '/',
controller: 'NavigationController',
activeTab: 1
});
}]);
})();
I've tried changing this for $scope to no avail.
You write ng-repeat in wrong way in your new.html partial page
it should be like
new.html
<div ng-repeat="user in users">
Correct syntax for ng-repeat is
<element ng-repeat="item in [1,2,3]">
Also you can use things like track by $index if you have duplicated values in your collection like [1,1,1].
Ref. https://docs.angularjs.org/api/ng/directive/ngRepeat
There are few issues in your code. Please change all this references to $scope and then quickly fix below html code:
<div ng-repeat="user in users">
It should work but update me otherwise also.
Working demo for your reference (route codes excluded for demo purpose only)
thanks,
Ashok
you have not written ng-repeat in right way change it to:
<div ng-repeat="user in users">

Categories

Resources