angular directive template stopped working - angularjs

I was using angular directive and it was working fine. But suddenly it stopped working and i don't know why. Here is my code:
<div id="main" data-ng-controller="Controller" data-ng-app="app">
<div class="stars">
<star-rating value="{{item.Value.Rate}}"></star-rating>
</div>
</div>
My angular code is here:
angular.module('app', ['ui.bootstrap']);
var app = angular.module('app', []);
app.directive('starRating', function () {
return {
scope: {
value: '='
},
template: '<div class="stars"><i class="fa fa-star" ng-repeat="r in entries"></i></div>',
controller: function ($scope) {
$scope.entries = _.range($scope.value);
}
}
});
app.controller('Controller', function ($scope, $location, $http) {
//
})
.config(function ($httpProvider, $locationProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json;
charset=utf-8";
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
i really don't know what i'm missing.

Related

Unknown provider: DashboardServiceProvider <- DashboardService <- DashboardController

even if I read a lot of solutions according my problem, still to have this Error.
This is my Controller:
#Controller
#RequestMapping( "/dashboard" )
public class DashboardController {
#RequestMapping( value = "", method = RequestMethod.GET )
public HttpEntity<String> dashboard() {
SimpleDateFormat sdf = new SimpleDateFormat( "dd-MM-yyyy" );
return new HttpEntity<String>( "Today is " + sdf.format( new Date() ) );
}
}
this is my index.jsp
<body ng-app="dashboard">
<div ng-controller="DashboardController">
<p>Nome: <input type="text" ng-model="nome"></p>
<p>Cognome: <input type="text" ng-model="cognome"></p>
<input type="button" value="LOGIN" ng-click="login()"/>
</div>
<jsp:include page="includes.jsp"></jsp:include>
<div ng-show="value==1">
{{data}}
</div>
<div ng-show="value==0">
{{ResponseDetails}}
</div>
</body>
this is my module
var Dashboard = angular.module( 'dashboard', ['DashboardService'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
my service
Dashboard.factory('DashboardService', function ($http) {
return {
dashboard: function(successCallback, errorCallback) {
$http.get("/dashboard")
.success(
function (response) {
$scope.data = response;
}
).error(
function (response) {
$scope.data = "ERROR!";
}
)
}
}
});
and finally my controller
angular.module("dashboard", [])
.controller( 'DashboardController', function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
});
My JSP page must only send the request to the DashBoardcontroller, that it has the return the page dashboard.jsp with the current date.
You must not inject dependencies in your module. Dependencies like service, factory have to be injected in controllers. By the way, don't forget to inject ngRoute.
Module becomes:
var Dashboard = angular.module( 'dashboard', ['ngRoute'] )
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/dashboard', {
templateUrl: '/WEB-INF/pages/dashboard.jsp',
controller: 'DashboardController'
});
}]);
Your controller code is good, just one thing: if you want to use a code compiler like Grunt, Gulp or Webpack, don't forget to add your dependencies as strings:
angular.module('dashboard')
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
I copied your controller with the service injection
.controller( 'DashboardController', ['$scope', 'DashboardService'], function ($scope, DashboardService) {
but in the end I had to write this
Dashboard.controller( 'DashboardController', ['$scope', 'DashboardService' , function ($scope, DashboardService) {
$scope.nome = "Daniele";
$scope.cognome = "Comandini";
var data = {
nome: $scope.nome,
cognome: $scope.cognome
};
$scope.value = 0;
var login = function() {
alert("LOGIN ON DASHBOARD");
DashboardService.dashboard();
};
$scope.login = login;
}]);
I mean I had to include the function into [], and not outside.

AngularJS not writing $scope variables to view

I have a very strange issue. Using AngularJS 1.5.8. With previous versions it didn't work either. Functions like ng-bind, ng-model, ng-submit work fine.
Click on "Inschrijven" http://adr-opleiding.ismiami.com/, second step "Postcode" and enter e.g. 1000. It will display Amsterdam. I used a div element w/ ng-bind="city". If I use {{city}} it will always display {{city}}. I can't get it to update from a controller.
angular.module('app', []).controller('HomeController', ['$rootScope', '$scope', '$stateParams', function($rootScope, $scope, $stateParams) {
$scope.$on('$viewContentLoaded', function() {
$scope.app.settings.htmlClass = $stateParams.htmlClass.website;
$scope.app.settings.bodyClass = '';
});
}])
.controller('WizCtrl', ['$scope', '$http', function($scope, $http) {
$scope.city = '';
$scope.printCity = function(){
if($scope.postcode.length == 4) {
$http({
method: 'POST',
url: '/db/get.php',
data: { action: 'retCity', zip: $scope.postcode }
})
.then(function success(response) {
$scope.city = response.data.city;
}, function error(response) {
});
}
}
}]);
And here's the HTML:
<div class="form-group">
<label for="wiz-postcode" class="col-xs-4 control-label">Postcode:</label>
<div class="col-xs-3">
<input class="form-control" type="text" name="wiz-postcode" id="wiz-postcode" style="width: 80px;" placeholder="Postcode" ng-keyup="printCity()" ng-model="postcode" onblur="this.value=this.value.toUpperCase()" />
</div>
<div class="col-xs-5" ng-bind="city" style="padding-top: 8px; font-size: 1.1em;"></div>
</div>
At the very top of the HTML I have a div element w/ the controller:
<div ng-controller="WizCtrl">
So the question is how come that $scope variables work fine for everything except updating the view w/ a variable like this {{test}}
A new Google search "angularjs variables in braces not working" got me to AngularJS-Twig conflict with double curly braces from which I learned that w/ AngularJS you can set the symbols w/ the variables start and endSymbol
var app = angular.module('app')
.config(
[ '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$interpolateProvider',
function ($controllerProvider, $compileProvider, $filterProvider, $provide, $interpolateProvider) {
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.service = $provide.service;
app.constant = $provide.constant;
app.value = $provide.value;
$interpolateProvider.startSymbol('::');
$interpolateProvider.endSymbol('::');
}
]);

For each Angular route I pull in a template. How do I enable the scopes and watches on those templates?

I have an main page with ng-view defined.
My routing pulls in several templates.
config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
})
.when('/view2', {
templateUrl: 'view2/view2.html',
})
.otherwise({redirectTo: '/view1'});
}]);
My First template looks like this:
<p>This is the partial for view 1.</p>
<div ng-controller="View1Ctrl">
<input type="text"
ng-model="search"
ng-model-options="{ debounce: 800 }"
placeholder="Enter full movie name"
autofocus />
</div>
The JS for this template looks like this;
'use strict';
angular.module('myApp.view1', [])
.controller('View1Ctrl', [function($scope, $http) {
$scope.$watch('search', function() {
fetch();
});
function fetch(){
alert("it werky");
}
}]);
Why am I getting the error: angular.js:13708 TypeError: Cannot read property '$watch' of undefined?
I'm essentially pulling in a template with models and directives defined on it but I don't think those are being run.
May be your dependencies are not getting injected, you are passing an array with the constructor function as it's only element.
Here is a working plunk.http://plnkr.co/edit/U2hxQPBZMVo2jaR4bwsq?p=preview
myApp.controller('View1Ctrl', ['$scope', '$http', function($scope, $http) {
alert ("jaiHo");
$scope.$watch('search', function() {
fetch();
});
function fetch(){
alert("it werky");
}
}]);
Try this:
'use strict';
angular.module('myApp.view1', [])
.controller('View1Ctrl', ['$scope', '$http', function($scope, $http) {
$scope.$watch('search', function() {
fetch();
});
function fetch(){
alert("it werky");
}
}]);
Note how I inject dependencies
Try this
(function () {
'use strict';
angular.module('myApp.view1', [])
.controller('View1Ctrl', function($scope, $http) {
var vm = this;
$scope.$watch('vm.search', function(newValue, oldValue) {
fetch(newValue, oldValue);
}, true);
function fetch(newValue, oldValue){
vm.newValue = newValue;
vm.oldValue = oldValue;
}
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp.view1">
<div ng-controller="View1Ctrl as vm">
<input ng-model="vm.search" type="text" />
<div>
Old Value: {{vm.oldValue}}
</div>
<div>
New Value: {{vm.newValue}}
</div>
</div>
</div>

Ng-route makes unwanted requests

Whenever I change a route, my app sends two unwanted GET request to the server. One fetches favicon and another one index.html file.
var app = angular.module('myApp', ['ngRoute', 'ngTagsInput']);
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
templateUrl: 'views/profile.html',
resolve: {
async: ['$http', function($http) {
return $http.get('/api/getUserInfo');
}],
dialogs: ['$http', function($http) {
return $http.get('/api/dialogs');
}]
},
controller: 'ProfileController'
})
.when('/friends', {
template: '<div friends-directive votes="model.user.votes" friends="model.friends"></div>'
})
.when('/comment', {
template: '<div comment-directive></div>'
})
.when('/dialogs', {
template: '<div dialog-directive messages="model.messages" dialogs="model.dialogs" new-messages="model.newMessages"></div>'
})
.when('/messages', {
template: '<div messages-directive messages="model.messages"></div>',
resolve: {
async: ['$http', function($http) {
return $http.get('/api/message');
}]
},
controller: 'MessagesController'
})
.when('/search', {
template: '<div search-directive></div>'
})
.when('/balance', {
templateUrl: 'views/balance.html'
})
.when('/users/:username', {
template: '<div users-directive user-profile="model.userProfile" switcher="switcher(path)" resource="model.resource"></div>',
resolve: {
async: ['$http', '$route', function($http, $route) {
return $http.get('/api/users/' + $route.current.params.username);
}]
},
controller: 'UsersController'
})
.otherwise({redirectTo: '/'});
}]);
app.run(['$http', '$window', function($http, $window){
var update = function(){
$http.get('/updatetime')
};
setInterval(update, 60 * 1000);
$window.onload = function() {
update();
}
}])
<base href="/">
<aside id="aside">
<div><img src="images/profile.svg"></div>
<div><img src="images/users.svg"></div>
<div><img src="images/search.svg"></div>
<div><img src="images/database.svg"></div>
<div><a ng-click="logout()"><img src="images/help.svg"></a></div>
</aside>
I just noticed these unwanted requests. Everything else works okay. Any idea what's going on?
FIXED: I didn't have favicon.ico file on my server. That's it!

ng-click inside ui-router not firing

i have a ngClick that is not firing.
this is my view:
<div ng-repeat="(key,val) in user[docParam]">
{{key}}<input type='text' class="form-control" name="{{key}}" ng-model="user[docParam][key]">
</div>
<div class="col-xs-6 col-xs-offset-3" ng-if="nextDoc(docParam)">
<a ui-sref="form.{{nextDoc(docParam)}}" class="btn btn-block btn-info">
Proceed To {{nextDoc(docParam)}} &nbsp <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
<div class="col-xs-6 col-xs-offset-3" ng-if="nextDoc(docParam)==false">
<a ng-click="save(user)" class="btn btn-block btn-info">
save &nbsp <span class="glyphicon glyphicon-circle-arrow-right"></span>
</a>
</div>
and this is app.js :
var $stateProviderRef = null;
var $urlRouterProviderRef = null;
var app= angular.module('app', [
//'ui.bootstrap',
'ui.router',
'ui.bootstrap',
'flow',
'controllers',
'services',
'filters',
'directives',
'xeditable',
'ngResource',
])
.run(['$rootScope', '$state', '$stateParams',
function($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
])
.controller('AController', ['$scope', function($scope) {} ])
.controller('SController', ['$scope', function($scope) {} ])
.config(['$locationProvider', '$stateProvider', '$urlRouterProvider', '$httpProvider',
function($locationProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
// XSRF token naming
$httpProvider.defaults.xsrfHeaderName = 'x-dt-csrf-header';
$httpProvider.defaults.xsrfCookieName = 'X-CSRF-TOKEN';
//$httpProvider.interceptors.push('httpInterceptor');
$stateProvider
.state('form', {
url: "/form",
templateUrl: '../partials/form/form.html',
controller:'formController',
});
$urlRouterProvider.deferIntercept();
$urlRouterProvider.otherwise('/form');
$locationProvider.html5Mode({
enabled: false
});
$stateProviderRef = $stateProvider;
$urlRouterProviderRef = $urlRouterProvider;
}])
.run(['$q', '$rootScope', '$http', '$urlRouter',
function($q, $rootScope, $http, $urlRouter) {
var $state = $rootScope.$state;
$http
.get("../lib/modules.json")
.success(function(data) {
angular.forEach(data, function(value, key) {
var getExistingState = $state.get(value.name);
if(getExistingState !== null){
return;
}
var state = {
"url": value.url,
"parent": value.parent,
"abstract": value.abstract,
"views": {}
};
angular.forEach(value.views, function(view) {
state.views[view.name] = {
templateUrl: view.templateUrl,
controller:'formController',
};
});
$stateProviderRef.state(value.name, state);
});
// Configures $urlRouter's listener *after* your custom listener
$state.go("form.personalInfo");
});
}
]);
controller:
.controller('formController', function($scope,DocParamData,$state,$http) {
'use strict';
$scope.docParam = $state.current.name.split('.');
$scope.docParam = $scope.docParam[1];
// we will store all of our form data in this object
$scope.saveUser = function(user) {
$http.post('/users', user).success(function(v){
return user;
}).error(function(err) {
if(err.field && err.msg) {
// err like {field: "name", msg: "Server-side error for this username!"}
$scope.editableForm.$setError(err.field, err.msg);
} else {
// unknown error
$scope.editableForm.$setError('name', 'Unknown error!');
}
});
};
the problem is with ng-click, it doesnt fire. not even a simple alert. ive allready tried everything in the threads, and i have no idea what is wrong.
i remember that there is some way to get a onclick to work with the scope..but cant find the right syntax..
You probably have errors in the console that you're not aware of.
I'm pretty sure dynamic {{...}} expression syntax is not supported by the ui-sref directive. See this issue.
Also name="{{key}}" should be ng-attr-name="{{key}}"

Resources