samedi 9 mai 2015

Angular - Testing a websocket wrapper with jasmine

I'm having trouble testing my websocket wrapper: data-service is my Angular service to wrap around the native browser WebSocket implementation.

Implementation:

angular.module('core').factory('dataService', function ($interval, webSocket) {

  var sock;

  function openSocket() {
    sock = new webSocket('ws://localhost:9988');
  }

  function isReady() {
    return sock.readyState === 1;
  }

  openSocket();

  $interval(function () {
    !isReady() && openSocket();
  }, 5000);
});

webSocket is window.WebSocket extracted to an angular constant.

Test:

describe('Data Service', function () {

  var dataService,
    ws;

  jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000;

  beforeEach(function () {
    module('core', function ($provide) {
      ws = jasmine.createSpy('constructor');
      $provide.constant('webSocket', ws);
    });

    inject(function (_dataService_) {
      dataService = _dataService_;
    });
  });

  it('should attempt to connect on load', function () {
    expect(ws).toHaveBeenCalled();
  });

  it('should attempt to reconnect every 5 seconds', function (done) {
    setTimeout(function () {
      expect(ws.calls.count()).toBe(2);
      done();
    }, 6000);
  });
});

should attempt to connect on load

passes: it was called once as expected.

should attempt to reconnect every 5 seconds

fails: no matter what timeout period I pass to setTimeout it's only ever called once. I'm wondering if this is due to the socket being re-instantiated every reconnect attempt with the new keyword. I'm not really familiar with how using new in javascript differs to using a normal function to construct an object.

Am I missing something? Or is the browser's WebSocket just a pain to test around?

Nesting ng-repeat at single level of DOM

I have nested collections, as follows:

[
  {
    name:    "foo",
    members: ["foo1","foo2"]
  }, {
    name:    "bar",
    members: ["bar1","bar2","bar3"]
  }, {
    name:    "qux",
    members: []
  }
]

From this, I would like to generate the following markup:

<tbody>
  <tr>
    <th scope="row" rowspan="2">foo</th>
    <td>foo1</td>
  </tr><tr>
    <td>foo2</td>
  </tr><tr>
    <th scope="row" rowspan="3">bar</th>
    <td>bar1</td>
  </tr><tr>
    <td>bar2</td>
  </tr><tr>
    <td>bar3</td>
  </tr>
</tbody>

It would also be acceptable to repeat the <th> cells in each row, if rowspan proves too awkward to work with:

<tbody>
  <tr>
    <th scope="row">foo</th>
    <td>foo1</td>
  </tr><tr>
    <th scope="row">foo</th>
    <td>foo2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar1</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar2</td>
  </tr><tr>
    <th scope="row">bar</th>
    <td>bar3</td>
  </tr>
</tbody>

What is the idiomatic way to accomplish a task like this using AngularJS? In particular, I'm struggling to see how one can perform a nested ng-repeat at a single level of the DOM (i.e. on the <tr> element).

AngularJS, Web API authentication

Problem Statement:

I am using AngularJS as my front end, I have a service layer to get/save data from/to database. Before doing this I want to authenticate the user and perform actions based on role of the user. I am using SQL Server as my database.

What I tried:

I tried having an endpoint expose and validate the user for every request. I tried having a session but unfortunately I somehow feel it is obsolete method and may be (because I have not tried on mobile) will not work fine with mobile.

What I am looking for

I am looking for token based authentication, to validate user against the SQL Server table and return a token and validate token for every request.

Can someone suggest me some links with custom database.

Note: If my request is not asking for too much, I would like to learn doing this using OWIN. If someone can suggest me OWIN method for my above request, I would be glad.

how to pass only two properties to a $scope variable

ANGULARJS Question:

I got an array of objects and I need to pass it to my $scope variable. THe property that's creating a problem for me in special is the 'user:' property. since it holds elements like the name and email it affects the way the filter i set in the HTML is filtering the objects I want to display. The object is a list of notes and I want to be able to filter them by content in the note( title and body text)

I have tried to delete the property user from the object with the code below, but that does not work. $scope.notes still loads that attribute.

Ideally I should be able to pass to $scope.notes only the title and body attributes. Any ideas of how to do that efficiently?

 var notes = notesService.notesObjectInService;
    for (var i = 0;  i < notes.length; i++) {
        delete notes[i].user;
    };

    $scope.notes = notes;

This is the json object passed to notes in the first line.

[{"id":184,
"title":"Mari",
"body":"Mae",
"created_at":"2015-05-09T03:23:04.250Z",
"updated_at":"2015-05-09T03:23:04.250Z",
"user_id":1,
"user":{"id":1,
"email":"vini@vini.com",
"created_at":"2015-04-24T22:49:21.797Z",
"updated_at":"2015-05-09T03:04:27.739Z",
"username":"vinivini"}}]

angular.js: Dynamic navigation depending on login status

I have following routing with athentication, which is done via a PHP-Script and MySQL:

app.config

app.config(['$routeProvider',
  function ($routeProvider) {
        $routeProvider.
        when('/login', {
            title: 'Login',
            templateUrl: 'partials/login.html',
            controller: 'authCtrl'
        })
        .when('/logout', {
            title: 'Logout',
            templateUrl: 'partials/login.html',
            controller: 'logoutCtrl'
        })

        .when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'partials/dashboard.html',
            controller: 'authCtrl'
        })
        .otherwise({
            redirectTo: '/login'
        });
  }])
    .run(function ($rootScope, $location, Data) {
        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            $rootScope.authenticated = false;
            Data.get('session').then(function (results) {
                if (results.uid) {
                    $rootScope.authenticated = true;
                    $rootScope.uid = results.uid;
                    $rootScope.name = results.name;
                    $rootScope.email = results.email;
                } else {
                    var nextUrl = next.$$route.originalPath;
                    if (nextUrl == '/signup' || nextUrl == '/login') {

                    } else {
                        $location.path("/login");
                    }
                }
            });
        });
    });

authCtrl

app.controller('authCtrl', function ($scope, $rootScope, $routeParams, $location, $http, Data) {
    $scope.login = {};
    $scope.signup = {};
    $scope.doLogin = function (customer) {
        Data.post('login', {
            customer: customer
        }).then(function (results) {
            Data.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };
    $scope.signup = {email:'',password:'',name:'',phone:'',address:''};
    $scope.signUp = function (customer) {
        Data.post('signUp', {
            customer: customer
        }).then(function (results) {
            Data.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };
    $scope.logout = function () {
        Data.get('logout').then(function (results) {
            Data.toast(results);
            $location.path('login');
        });
    }
});

Now I want to change the navigation depending on the login-status. If user is logged in there should bei a logOUT-Button and a link to the dashboard. If the user isn't logged in it should look like this

sample for unlogged-in user

<header id="navigation">
    <nav id="main">
        <ul>
            <li id="login"><a href="#/login" class="btn"><i class="fa fa-power-off"></i> Login</a></li>
        </ul>
    </nav>
</header>

What is the best way for creating the navigation? Should it be a seperate template?

QuantumUI Pagination

I'm new to Angularjs and trying to do pagination in Quantumui for which i get data from RestAngular, i can able to create pagination using ng-Table successfully for the same connects but i'm but cant able to do the same with Quantumui's '$pageableProvider' i tried it as below help me to understand the concept of Quantumui.

I Get the Following Error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module restAngular due to:
Error: [$injector:modulerr] Failed to instantiate module nqPageable due to:
Error: [$injector:nomod] Module 'nqPageable' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument

My App.js:

i use RestAngular to get data

var get = angular.module('get', []);

var myApp =angular.module('restAngular',[
    'restangular',
    'get',
    'create',
    'ngSanitize',
    'ngAnimate',
    'ngQuantum',
    'nqPageable',
    'ngTable'
])
myApp.config([
    'RestangularProvider',
    '$pageableProvider',
    function(RestangularProvider,$pageableProvider){
        RestangularProvider.setBaseUrl('http://localhost:1337/lb4b/api/');
        var mydefaults = {
            seletable : true,
            pageNumber : 1,
            pageSize : 5
        }
        angular.extend($pageableProvider.defaults, mydefaults)
    }
])

get.controller('getCtrl',[
    'Restangular',
    '$scope',
    'ngTableParams',
    '$filter',
    function(Restangular,$scope,ngTableParams,$filter){

        var userData = Restangular.all('User').getList().then(
            function(user){
                $scope.users = user;
                //This is to check the data has passed succes
                console.log(user[0].business_category);
                //console.log(user.length);            
                //console.log('x  is :'+x );
            }
        )
    }
]);

Can Some one help me to understand the concept of pagination used in quantumui.

Thanks in advance.

Front-end development with conditional HTTP and HTTPs routes

I am currently using MEAN stack for web development. My questions is how do I mix HTTP and HTTPs on the same website?

For most scenarios I am communicating with the back-end using HTTP protocol. And for some pages I absolutely need to use HTTP (For example #!/shop/:shopId route, I used an iframe that displays info from other websites. and some pages I need to HTTP GET some info from other API services.) It seems that I cannot achieve these with HTTPs setup.

For some cases I am communicating with the back-end using HTTPs (such as #!/money route) ...etc. And apparently you need HTTPs with money involved.

My back-end has middlewares setup so that if you request /money using HTTP it will return some error (currently returning 301 but not sure if this sound correct..).

But I am not sure how do I proceed with front-end development. For angular should I just do some configurations so when the route consists of /money I just reload the whole page in HTTPs or should I just explicitly make sure the links look someting like this?

<a ng-href="http://ift.tt/1GVe3sV">money page</a>

But that seems like a lot of hard-coding for me.

My question is: 1. Am I thinking in the right direction?
2. Is it doable?

Thanks and any idea is greatly appreciated!

angular js ng-view returns blanc partials -- Express/ Jade

I am writing an angular application following a tutorial. To my surprise, i followed exactly and my node js is starting fine without an issue. However, my angular is not returning the template as suppose to . I saw a similar problem here same tutorial and the same issue. However, the question was not answered . Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Althought i am thinking that shouldn't be an issue because i am starting with a partial view which is part of a page. When i run, my page return black. I inspect the element and ensured that all the js and css where loaded. When i view the source, a html source below was generated.

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail . please where do i go wrong ? I have tried everything possible. I even restarted the tut yet still blanc. any help would be appreciated.

How to update html header after login in an angular/node.js application?

I am trying to get a header to update after login. I have used both $on and $watch in this effort to no avail. When I refresh it works correctly. Code is as follows below.

header.html (missing excess nav bar code for simplicity)

<li><a ng-href="#/login" ng-hide="showMenu">Login</a></li>
<li><a ng-href="#/signup" ng-hide="showMenu">Signup</a></li>
<li><a href="javascript:" ng-click="logout()" ng-show="showMenu">Logout</a></li>

app.js

$stateProvider
  .state('app', {
    url: '',
    views: {
      'header': {
            templateUrl: 'views/partials/_header.html',
            controller: 'HeaderCtrl'
      }
    }
  })

header.js (The broadcast fires correctly as demonstrated by the console.logs)

angular.module('urbinsight')
.controller('HeaderCtrl', function ($scope, $rootScope, $state, $location, UserAuthFactory, AuthFactory) {

$scope.logout = function () {
  UserAuthFactory.logout();
  $rootScope.$broadcast('loginStateChange');
  $location.path('/');
};

$scope.showMenu = AuthFactory.loggedStatus();

$rootScope.$on('loginStateChange', function(){
  console.log($scope.showMenu)
  $scope.showMenu = AuthFactory.loggedStatus(); 
  console.log($scope.showMenu)
  })
})

authService

angular.module('urbinsight.services')
.factory('AuthFactory', function ($window) {
var isLogged = false;

return {
  check: function() {
    if ($window.sessionStorage.token && $window.sessionStorage.user) {
      isLogged = true;
    } else {
      isLogged = false;
      delete this.user;
    }
  },
  loggedStatus: function() {
    return isLogged;
  },
  changeLoggedStatus: function() {
    isLogged = !(isLogged);
  }
};
})

Please tell me what I am doing wrong.

angular partial not rendering with jade

I am building an angular app following a tut. However, my angular ng-view is not rendering. I have seen a similar question here yet it has not been answered. Below is my dir structure

app.js

var app = angular.module('app', ['ngResource', 'ngRoute']);

angular.module('app').config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true);
    $routeProvider
        .when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});
});


angular.module('app').controller('mainCtrl', function($scope){
    $scope.myVar = "Hello Angular";
});

My layout.jade

doctype html
head
   link(rel="styleSheet",href="css/bootstrap.css")
   link(rel="styleSheet",href="vendor/toastr/toastr.css")
   link(rel="styleSheet",href="css/site.css")
body(ng-app='app')
   block main-content
   include scripts

My main.jade

h1 This is a partial
h2 {{ myVar }}

The route in my server.js are set as

app.get('partials/:partialPath',function(req,res){
    res.render('partials/' + req.params.partialPath);
});
app.get('*', function(req,res){
    res.render('index');
});

my index.jade

extends ../includes/layout

block main-content
    section.content
       div(ng-view)

Although I am thinking that shouldn't be an issue because I am starting with a partial view which is part of a page. When I run my page it returns black. I inspected the elements and ensured that all the js and css where loaded. The html source below was generated on my page:

<!DOCTYPE html>
<head><link rel="styleSheet" href="css/bootstrap.css">
<link rel="styleSheet" href="vendor/toastr/toastr.css">
<link rel="styleSheet" href="css/site.css">
</head>
<body ng-app="app">
  <section class="content">
   <div ng-view></div></section>
   <script type="text/javascript" src="vendor/jquery/dist/jquery.js"></script><script type="text/javascript" src="vendor/angular/angular.js"></script>
<script type="text/javascript" src="vendor/angular-resource/angular-resource.js"></script>
<script type="text/javascript" src="vendor/angular-route/angular-route.js"></script><script type="text/javascript" src="app/app.js"></script>
</body>

I was suspecting routeProvider from my app.js here

.when('/', { templateUrl: 'partials/main', controller: 'mainCtrl'});

tried

.when('/', { templateUrl: '/partials/main', controller: 'mainCtrl'});

All to no avail. Please where do I go wrong ? I have tried everything possible. I even restarted the tut yet still blank. Any help would be appreciated.

Angular: add HTML markup to string depending on keyboard input

I have an inputfield and I would like to print the input to the screen while I'm filling in the inputfield. However I'd like to scan the input text, to print certain words bold.

So for example, if I'm typing: "Hello how are you?"

I want it to be printed under the input field but Hello has to be in bold: Hello how are you ?

Is there a way in Angular to achieve this?

How to set ng-attr-title using ternary operator in Angularjs?

I am very new to Angularjs. I want to set a value for title attribute, based on a boolean variable.

Sample code attached here.

 <tr ng-repeat="doc in $data" ng-class="{{doc.is_today}} ? 'highlight' : ''" 
                                        ng-attr-title="({{doc.is_today}}) ? 'Today' : ''"> 
     <td>1</td>
     <td>2</td>
     <td>3</td>
     <td>4</td>
     <td>5</td>
</tr>

Thanks,

Facebook connect using django rest framework and angularjs?

Im developing a website in which the user can signup using facebook connect, when he signup we will collect all his personal details from fb and store it in a user table. This user table id is used as foreign key in many other tables. My questions are,

  1. How can I implement fb signup using angularjs and DRF.
  2. Once the user logs in how can I get the corresponding data from related table since I will pass only the authentication token(Do I need to get user id matching the auth token?)
  3. We collect all his details only for the first login, how can we find out whether the user is already registered or not?
  4. Is there any valuable material available online for this?

Im using python-social-auth and oauth for the above, but they are very confusing.

AngularJS disable button during factory AJAX call

I want to disable a button while a factory AJAX request is running (after the button was clicked) and I used this SO answer as a starting point on how to do that, but I can't get my custom directive click-disable to execute the controller method (using ng-click works fine).

I suspect my directives doesn't get "compiled" at page load, directives with simple templates also don't seem to work.

js/services.js:

var raspiSurveillanceServices= angular.module('raspiSurveillanceServices', ['ngResource']);

raspiSurveillanceServices.factory('Camera', ['$resource',
    function($resource) {
        return $resource('/api/cameras/:id');
    }]);

js/directives.js:

var raspiSurveillanceDirectives = angular.module('raspiSurveillanceDirectives', []);

raspiSurveillanceDirectives.directive('clickDisable', function() {
    return {
        restrict: 'A',
        scope: {
            clickDisable: '&'
        },
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.prop('disabled', true);

                scope.clickDisable().finally(function() {
                    element.prop('disabled', false);
                });
            });
        }
    };
});

js/controllers.js:

raspiSurveillanceControllers.controller('CameraListCtrl', ['$scope', 'Camera', function ($scope, Camera) {

    $scope.cameras = Camera.query();

    $scope.deleteCamera = function(camera) {
        return Camera.delete({ id: camera.id}).$promise.then(
            function(value) {
                // Remove item from array
                var index = $scope.cameras.indexOf(camera);
                $scope.cameras.splice(index, 1);
            },
            function(error) {
                alert("Delete failed");
            }
        )
    };

}]);

js/app.js:

var raspiSurveillanceApp = angular.module('raspiSurveillanceApp', [
  'raspiSurveillanceControllers',
  'raspiSurveillanceServices',
  'raspiSurveillanceDirectives',

  'xeditable'
]);

.blade.php:

<tr ng-repeat="camera in cameras">
    ...
    <button class="btn btn-danger" click-disable="deleteCamera(camera)">Delete</button>
</tr>
...
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-resource.min.js"></script>

<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="js/directives.js"></script>

Angular Material is slow to load?

When I load my website, sometimes I have to refresh a few times because the Angular Material style (and logic) don't load fine. Anyone know why can it be?

Click event on Angular Material Design Gridlist

I'm going through Angular Material Design Gridlist and they have not mentioned anything about handling hover/click on the grids. So, is there a way to do it or should I use buttons inside each grid to handle click events ?

Angular Ui router allowing API route

I have an AngularJS SPA Template for visual studio in my project and a WebApi 2.2 in the same project. But everytime I go to a /api link it gives me the 404 error

so I figured the routing isn't setup correct. Thisis the route provider:

$stateProvider
    .state('home', {
        url: '/',
        templateUrl: '/views/index',
        controller: 'HomeCtrl'
    })
    .state('about', {
        url: '/about',
        templateUrl: '/views/about',
        controller: 'AboutCtrl'
    })
    .state('units', {
        url: '/units',
        layout: 'basic',
        templateUrl: '/views/units',
        controller: 'UnitCtrl'
    })
    .state('otherwise', {
        url: '*path',
        templateUrl: '/views/404',
        controller: 'Error404Ctrl'
    });

$locationProvider.html5Mode(true);

So I don't know if I should add a state for the api or change the otherwise path? and what to add

Get the users location with ipaddress in Angularjs

I want to get the users location parameters in my Angularjs app like Country, city, state, postalcode etc based on the ip address.

Single Page Application over IIS vs Node + IIS?

We are developing a single page application using AngularJs having an index file at the root which will be served by web server to client. Currently when developing, we are using Node with express server. We need to deploy this application to azure. There are two deployment options available.

  1. Deploy either as web application on azure (I think its IIS server in this case)
  2. Or deploy on IIS using IIS Node module

We need to have a rewrite rule, which will serve index page for every other request to server in both cases.

Which is better deployment model or if anyone can suggest another option available for SPA on Azure?

Unknown provider: ngMessagesProvider with require.js

I am trying to use ngMessages in my controller:

I am setting up my require.js config:

require({

  // libraries dependencies (fallback support)
  paths: {

    jquery: [
      'vendor/jquery/2.1.3/jquery.min'
    ],

    bootstrap: [
      'vendor/bootstrap/3.3.2/js/bootstrap.min'
    ],

    angular: [
      'vendor/http://ift.tt/1P7EGVe'
    ],

    angularResource: [
      'vendor/http://ift.tt/1KSXhP2'
    ],

    angularAnimate: [
      'vendor/http://ift.tt/1P7EGVg'
    ],

    ngMessages: [
      'vendor/http://ift.tt/1KSXj9J'
    ],

    uiBootstrap: [
      'vendor/angular-ui/bootstrap/0.12.0/ui-bootstrap-tpls.min'
    ],

    uiRouter: [
      'vendor/angular-ui/ui-router/0.2.13/angular-ui-router.min'
    ],



  },

  // define js scripts dependencies
  shim: {

    'bootstrap': {
      deps: ['jquery']
    },

    'angular': {
      deps: ['bootstrap'],
      exports: 'angular'
    },

    'angularResource': {
      deps: ['angular']
    },

    'angularAnimate': {
      deps: ['angular']
    },

    'ngMessages': {
      deps: ['angular']
    },

    'uiBootstrap': {
      deps: ['bootstrap',  'angular']
    },

    'uiRouter': {
      deps: ['angular']
    },


  },

  priority: [
    'angular'
  ],

  deps: ['./ng.app']

});

and in module.js I am requiring ngMessages:

define(function(require) {
  'use strict';

  var angular = require('angular');
  require('angularResource');
  require('ngMessages');

  require('uiRouter');
  require('uiBootstrap');

  // angular module definition
  return angular.module(
    // module name
    'companies',

    // module dependencies
    [
      'ngResource',
      'ngMessages',

      'ui.router',
      'ui.bootstrap',

      require('shared/fend/input-utils/package').name,
      require('shared/fend/pagination/package').name
    ]
  );

});

and then in my controller I am trying to inject ngMessages:

define(function(require) {
  'use strict';

  var module = require('../module');
  require('../resources/rest');


  module.controller('CompaniesNewCtrl', CompaniesNewCtrl);


  CompaniesNewCtrl.$inject = [
    '$rootScope', '$scope', '$state',
    'CompaniesResource',
    'InputFocusFactory', 'ngMessages'
  ];

  function CompaniesNewCtrl($rootScope, $scope, $state, resource, input, ngMessages) {... })

but i am getting error: Error: $injector:unpr Unknown Provider Unknown provider: ngMessagesProvider

What am I doing wrong?

Ui Router tabs with routing

I'm using UI-Router and I need to hook up tabs where the url changes as well. So for example, I have a page with 3 sublinks:

  1. Customer Overview (templates/customer.overview.html): http://ift.tt/1KSWo9k
  2. Customer Settings (templates/customer.settings.html): http://ift.tt/1P7DjG2
  3. Customer Contact Info (templates/customer.contact.html): http://ift.tt/1KSWoGk

All three of these pages should be injected into one main customers.main.html page that includes the links.

My states are defined as follows:

  $stateProvider
    .state('customer', {
      abstract: true,
      url: '/customer',
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.overview.html');
      }
    })
    .state('customer.overview', {
      url:'/:id/overview',
      controller: ''
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.settings.html');
      }
    })
    .state('customer.contact', {
      url:'/:id/contact',
      controller: ''
      templateProvider: function($templateCache) {
        return $templateCache.get('templates/customer.contact.html');
      }
    });

And I have a customers.main.html page:

<div class="tabs" ng-controller="TabsCtrl as tabs">
   <a ng-repeat="tab in tabs" ui-sref='{{tab.route}}' ng-bind="tab.label">
</div>

TabsCtrl

angular.module('customers')
  .controller('TabsCtrl', [
    function() {

    var self = this;

    self.tabs = [
      {
        label: 'Overview',
        route: 'customer.overview',
        active: false
      },
      {
        label: 'Settings',
        route: 'customer.settings',
        active: false
      },
      {
        label: 'Contact',
        route: 'customer.contact',
        active: false
      }
    ];

    self.selectedTab = self.tabs[0];
  }
]);

However, this doesn't seem to be working correctly. The ui-sref directive when I click always resolves to something like: /customers//settings. It's not picking up the :id.

Any help?

What is the correct way to install and test how to install angular ui bootstrap in my application if I dont have bower or npm for project?

I downloaded ui-bootstrap-0.12.0.min.js (0.12.0 because I am upgrading an application and the angular.js used in the application is 1.2.x) and included it in my application via <script> tag. I tried testing by creating components like popover and dialog but none of them seem to be triggering.

Do I need to do something else?

Angular form validation on Yii Form

I am using AngularJS v1.3.15 for form validation within Yii dynamic form but it seems angular validation works on input names. the problem is that name of inputs are in array format such as: name="LoginForm[username]". i am copying my code here:

   <div class="col-md-4 col-md-offset-4 m-t-lg" ng-app="validationApp" ng-controller="mainController">
            <section class="panel">
                <header class="panel-heading text-center"><strong>Admin Sign in </strong> </header>
                <?php 
                        $form=$this->beginWidget('CActiveForm', array(
                            'id'=>'formLogin',
                            'htmlOptions'=> array('name'=>'userForm', 'class'=>'panel-body', 'ng-submit'=>'submitForm($event)', 'novalidate'=>'true'),
                            'action'=>'#',
                            'enableAjaxValidation'=>false,
                        )); 
                    ?>
                    <div class="form-group" ng-class="{'has-error' :  userForm.username.$invalid && !userForm.username.$pristine}">
                        <label class="control-label">Email</label> 
                        <?php echo $form->emailField($model, 'username', array('placeholder'=>'test@example.com', 'class'=>'form-control', 'ng-model'=>'user.username', 'ng-pattern'=>"/^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", 'required'=>'true', 'id'=>'username')); ?>
                        <?php echo $form->error($model,'username'); ?>
                    </div>
                    <div class="form-group" ng-class="{'has-error' :  userForm.password.$invalid && !userForm.password.$pristine}">
                        <label class="control-label">Password</label> 
                        <input type="password" placeholder="Password" ng-minlength="6" class="form-control" name="password" ng-model="user.password" required>
                    </div>
                    <div class="checkbox">
                        <label> <input type="checkbox"> Keep me logged in
                        </label>
                    </div>
                    <button type="submit" class="btn btn-info" ng-disabled="userForm.$invalid">Sign in</button>
                <?php $this->endwidget(); ?>
            </section>
        </div>
    </div>

And here is script code for angular controller:

      var app = angular.module('validationApp',[]);
         app.controller('mainController', function($scope) {
            $scope.submitForm = function($event){
            if ($scope.userForm.$valid){
                $scope.submit();
            } else $event.preventDefault();
         } 
      });

it works fine if i change names of input as a single word such as "username" and "password" but its not working in current situation with having name "LoginForm[username]". its working fine with password field because its plain name but same is not true with username field.

pikaday angular sending date format in json

how do i send the pikaday plugin date format in my json using ng-model

i had been trying this

<input pikaday="" ng-model="products_chosen[$index].from.getDate()" placeholder="From">

js:

    $scope.products_chosen = [{"from":new Date(),"till":new Date(),"checkbox":0}];
    $scope.productChange = function(index, checkbox){
        if(checkbox==1){
            $scope.products_chosen.push({"from":"","till":"","checkbox":0});  
        }
        else{
            $scope.products_chosen.splice(index,1);
        } 
    }

Angular oi.multiselect how to get value of current changed modal

I need to pick the value of a model that has changed. I am using the oi.multiselect in angular. Each time I pick the model it gives me the initial value in it instead of the current changed one. Here is my html part of the code:

               <oi-multiselect
                ng-options="item for item in clientx"
                ng-model="bundlex"
                multiple
                placeholder="Select clients"
                ></oi-multiselect>

The model "bundlex" values initially are ["Brad Stan"," Calins mark"] reading from the controller. But after in select new values from the drop down the model changes to ["Brad Stan"," Calins mark"," Xavier Nato"," Frank Sunatra"]. When I post the model after changing it, it seem to only hold the initial values and not the new/current one. How can I solve this? Thank you. Here is a link to an example: http://ift.tt/1bFqlgu

Material design on web, who's closest to achieve it?

Material design is a unified system of visual, motion, and interaction design that adapts across different devices.

http://ift.tt/1jq9kdg

I am differentiating between frameworks, if I'd choose between one of these:

The polymer project: http://ift.tt/1GALwxu

Using Angular.js: http://ift.tt/1vyDYkS

Or the other CSS Play, using bootstrap:

materializecss.com/

http://ift.tt/XTuIxj

www.muicss.com/

This function's cyclomatic complexity is too high. (38)

I have a switch case statement for my filters. But it throws me complexity issues of 39 can u help me solve it??

Below is my sample code. It includes some more cases.

    angular.forEach(docsClone, function(doc) {
                var added = false;
                angular.forEach($scope.filterOptions, function(opt) {
                    if (!added) {
                        switch (opt.AttributeId) {
                            case 'documentStatus':
                                if ((doc.documentStatus !== undefined && doc.documentStatus !== null && doc.documentStatus.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planStatus':
                                if ((doc.planStatus !== undefined && doc.planStatus.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planFamily':
                                if ((doc.planProductFamily !== undefined && doc.planProductFamily !== null && doc.planProductFamily.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'planYear':
                                planYear(doc, opt.AttributeValue, filteredDocs, added);
                                break;
                            case 'documentType':
                                if ((doc.documentType !== undefined && doc.documentType !== null && doc.documentType.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'businessEntity':
                                if ((doc.businessEntity !== undefined && doc.businessEntity !== null && doc.businessEntity.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'productClass':
                                if ((doc.productClass !== undefined && doc.productClass !== null && doc.productClass !== null && doc.productClass.indexOf(opt.AttributeValue) !== -1) ||
                                    (doc.planProductClass !== undefined && doc.planProductClass.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
                            case 'productType':
                                if ((doc.productType !== undefined && doc.productType !== null && doc.productType.indexOf(opt.AttributeValue) !== -1) ||
                                    (doc.planProductType !== undefined && doc.planProductType.indexOf(opt.AttributeValue) !== -1)) {
                                    filteredDocs.push(doc);
                                    added = true;
                                }
                                break;
    }

Angular Bootstrap DateTimePicker - Highlight Today Date on embedded Calender

Please accept my apologies if i had any mistakes in my post. This is my first post here. But, i am not new to StackOverflow. Correct me if any.

I am using angular-bootstrap-datetimepicker library from the below url: Link to library

I am currently embedding the calender on the page. I am using angular.js, moment.js, grunt and bower. Absolutely no issue loading the calender and can even select a date and display the selected date as well.

Here is the sample code:

<div>
  Selected Date: {{ data.embeddedDate | date:'yyyy-MMM-dd' }}
  <datetimepicker data-ng-model="data.embeddedDate" data-datetimepicker-config="{ startView:'day', minView:'day'}" />
</div>

I am trying to highlight today's date automatically when the datetimepicker shows on the page. As you can see, in the config options, i could set the default view and min view.

Note: I tried to mimic the working code (till now) in Plunkr but, its not showing the calendar. I added all libraries as well. Anyways, that's just for idea only. If i could get the Plunkr working, i will update again. Here is the link to Plunkr.

Any suggestions (regarding highlight today date by default) will be appreciated.

What's the main purpose of $scope in AngularJS controller?

Yesterday, I saw my co-worker write a huge controller with only one "god object" $scope that should look like this following code.

myApp.controller('ComplexController', ['$scope', function($scope) {

 $scope.firstTab = {
    init: function () {
      $scope.firstTab.data1.foo = $scope.firstTab.DefaultData1.foo;

      $scope.$watch('firstTab.data1.foo', function (){
        // do something
      });
    },
    defaultData1: {
      foo: 'bar'
    },
    data1: {
      foo: 'bar',
      publiclyUsedMethod1: function () {},
      publiclyUsedMethod2: function () {},
      privatelyUsedMethod1: function () {},
      privatelyUsedMethod2: function () {},
      privatelyUsedMethod3: function () {},
      privatelyUsedMethod4: function () {},
      privatelyUsedMethod5: function () {}
    },
    data2: {
      // Same code pattern as above
    },
    data3: {
      // Same code pattern as above
    },
    data4: {
      // Same code pattern as above
    }
  };

  $scope.secondTab = {
    // Same code pattern as above
  };

  $scope.thirdTab = {
    // Same code pattern as above
  };

  $scope.refresh = function(){
    // do something
  };

  $scope.$watchCollection('[$scope.firstTab.data1.foo, $scope.secondTab.data1.foo, $scope.thirdTab.data1.foo]',function(newValues,oldValues){
    // some logic
    $scope.refresh();
  });

  $scope.firstTab.init();
  $scope.secondTab.init();
  $scope.thirdTab.init();
}]);

What do you think which this pattern? What's the main purpose of $scope object? Is it OK to store every private and public object in $scope object?

Thanks,

SEO with angular.js application

In my application I used angular.js as a client side technology now i want my site SEO friendly I found the solution but I am little bit confused about it that is sitemap.xml is required or not for angular seo ?

Preventing multiple clicks in angularjs

When I want to delete a record from my page I need to show confirmation message before deleting. For this I have used anchor and ng-click='delete()' for deleting such row. Here user can click on anchor multiple times. It is a serious problem because confirmation popup render multiple times. My example is a sample. In my project I have faced too many problems like that.

Angular Error - Can't interpolate: (device.osVersion) Android 4.0.3

So I am running the Supersonic demo template on my Android phone, and I keep getting this error that is preventing the app from loading the page:

Can't interpolate: {{device.osVersion | strReplace:'_':'.'}} TypeError: Cannot read property 'replace' of undefined

Page setup tutorial page: http://ift.tt/1bFlxrs

Screenshot of debug console:

enter image description here

This is the raw untouched demo from AppGyver, so it should work out of the box! This does work on my iPad though so it seems to be an error with Android. I am running the app through the AppGyver Scanner on my phone.

Android version: 4.0.3

This is what the app screen looks like (the black space being the error as there should be text and buttons there):

enter image description here

What are the existing and recommended solution for authentication using Oauth in Java as backend and Angular as frontend?

I have an application in Java and using angular as frontend. I have checked couple of authentication solution including oauth.io (It's not for free), oauth-ng etc. but as I am new to this technology stack I am not sure about this. Any thoughts/inputs will be highly appreciated.

pikaday angular sending json format

how do i send json date format using pikaday angular plugin using ng-model.

i have been trying this

{{product.product_name}}
{{products_chosen[$index]}} {{myPickerObject}}

js:

    $scope.products_chosen = [{"from":new Date(),"till":new Date(),"checkbox":0}];
    $scope.productChange = function(index, checkbox){
        if(checkbox==1){
            $scope.products_chosen.push({"from":"","till":"","checkbox":0});  
        }
        else{
            $scope.products_chosen.splice(index,1);
        } 
    }

showing Time from database in Timepicker directive Angular

I'm using timepicker there is an error to getting data from database : here is what should it be :

VisitDate: "2015-05-21T17:30:00"  

here is what i get :

21:00  



<timepicker ng-model="visitPlaceViewModel.VisitDate" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian" class="timePicker"></timepicker>

How to create a bill system with Node.js and front-end angular.js

How to create my first any billing system application by users node.js and angular js

very starnge behaviour with for loop and data-ng-init()

     I was trying to pass array of ids from controller to custom directive and in custom directive i need to get the whole object from server using some api and need to display it using ng-repeat. but when page gets loaded it should display, should not use any click events and all. 

here is my controller.

   $scope.$on('itemSelectedEvent', function (event, args) {
    $scope.selectedId = args.selectedId;
     $scope.searchId = args.searchId;
     $scope.searchType = args.searchType;
     getOrg($scope.selectedId).fetch({'searchType': $scope.searchType}).$promise.then(
              function (value) {
    switch($scope.data.searchType)

    {
    case 'tei_org' :
    $scope.recipientsOrgIdArr.push(data.relatedEntityInstanceId);

//need to pass this array of ids to directive
    break;
                 case 'tei_person' :
    $scope.recipientsPeopleIdArr.push(data.relatedEntityInstanceId);
//need to pass this array of ids to directive

      break;
                        }
    })
    });

my html file...

<search  searchobj="tei_org"  selecteditemslist="recipientsOrgIdArr"   searchid="organisation" />

sending array of ids (recipientsOrgIdArr) to the directive like this .

my directive html

{{list}}x

display(selecteditemslist,searchid,searchobj) function should get call when page is loaded

display() contains

  $scope.display = function (list, searchid, searchobj) {
    for (var i = 0; i < list.length; i++) {
            getOrg(list[i]).fetch({
                'searchType': searchobj
            }).$promise.then(
                function (value) {
    var data = {
                        'id': $scope.displayItem.id,

                        'item': $scope.displayItem.displayConfig[0].propertyValue
                    };
                    $scope.item.push(data.item);
    });
    }
    }

i had strucked with three problems.... 1) i dont know whats going wrong data-ng-init() was not getting call

2) my for loop is repeating twice of the length, i.e if length is 2 it was looping 4 times and iam getting duplicate items while displaying.

3) last thing is while displaying previous items aslo getting displayed but my requirment is they have to become null only current items should display.

please friends help me to solve this problem

Is it safe to use jQuery in _Layout.cshtml for a large Angular application?

I realise this question is somewhat broad, but I'm hoping I can provide enough contextual detail to narrow it down a bit. In a project I am very new to, one of my tasks is to add a confirmation dialogue when the user clicks the logout link. I have changed the link as follows, in _Layout.cshtml:

<div class="row inner">
    @if (Request.IsAuthenticated)
    {
        using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { @id = "logoutForm", @class = "col-md-8 col-md-offset-2 rightText" }))
        {
            @Html.AntiForgeryToken()
            <a href="@Url.Action("CreateNewMlamApplication", "MlamApplication")"><img src="/img/icons/plusIcon.png" class="icon" /></a>
            <a href="@Url.Action("Index", "Home")"><img src="/img/icons/documentIcon.png" class="icon" /></a>
            @* BKMOD <a href="javascript:document.getElementById('logoutForm').submit()"><img src="/img/icons/gearIcon.png" class="icon" /></a>*@
            <a class="logout-link-confirm" href="#" ><img src="/img/icons/gearIcon.png" class="icon" /></a>
        }
    }
</div>

Then, I hook a handler up to logout-link-confirm, at the bottom of the layout:

    <script>
        $(function() {
            $(".logout-link-confirm").click(function() {
                $('#modalLogoutConfirmation').modal('show');
            });
            $(".logout-link-final").click(function () {
                $('#logoutForm').submit()
            });
        });
    </script>
    @RenderSection("scripts", required: false)
</body>

And in the modalLogoutConfirmation popup, I perform the actual logout when the user confirms their choice: $('#logoutForm').submit().

This has nothing to do with angular directly, as angular only kicks in on some of the body views in this layout, but it is loaded, and I am a little concerned of any side effects my jQuery may introduce.

Angular New Router and grandchildren routes

I cannot find any examples on how to make grandchildren routes in the Angular New Router (1.4).

As I understand from a tutorial the router config is per component. And a component is self-contained and not aware of other components.

If I have a users component, and this component gives all users, and then this components has a child component that gives info on a specific user.

Is the following directory structure correct?

/app.js /app.html /components/users/users.js /components/users/users.html /components/users/components/user/user.js /components/users/components/user/user.html

Where /app.js contains the following route config:

$router.config([
 {path: '/users', component: 'users' }
]);

And /components/users/users.js contains the following route config:

$router.config([
 {path: '/user', component: 'user' }
]);

So the path in this example would be /users/user.

I probably have misunderstood, because when I tried it, it did not work. So anybody knows a tutorial or could enlighten me on how this really should be done?

Angular.module is not working

I am new to Angularjs and currently practising it .I have a simple example like this .

My View Index.cshtml

<div ng-app="MyApp">    
<div class="show-scope-demo">
        <div ng-controller="MainController">
            <p>Good {{timeOfDay}}, {{name}}!</p>
            <div ng-controller="subController1">
                <p>Good {{timeOfDay}}, {{name}}!</p>
                <div ng-controller="subController2">
                    <p>Good {{timeOfDay}}, {{name}}!</p>
                </div>
            </div>
        </div>
    </div>
</div>

and my controller is MyJsScript.js

(function (angular) {

angular.module('MyApp', []).controller('MainController', ['$scope', function ($scope) {
    $scope.timeOfDay = 'morning';
    $scope.name = 'sapan';
}]);
angular.module('MyApp', []).controller('subController1', ['$scope', function ($scope) {
    $scope.name = 'sapan';
}]);
angular.module('MyApp', []).controller('subController2', ['$scope', function ($scope) {
   $scope.timeOfDay = 'Evening';
    $scope.name = 'Tapan';
}]);
})(window.angular);

in this case I am getting error "[ng:areq] Argument 'MainController' is not a function, got undefined" But if I am changing my controller like this

(function (angular) {
var myApp = angular.module('MyApp', []);
myApp.controller('MainController', ['$scope', function ($scope) {
    $scope.timeOfDay = 'morning';
    $scope.name = 'sapan';
}]);
myApp.controller('subController1', ['$scope', function ($scope) {
    $scope.name = 'sapan';
}]);
myApp.controller('subController2', ['$scope', function ($scope) {
    $scope.timeOfDay = 'Evening';
    $scope.name = 'Tapan';
}]);
})(window.angular); 

It is working perfectly without any error .

Can anyone please tell me what is the exact difference between these two syntax.

vendredi 8 mai 2015

how to create multiple js files from index.html using grunt usemin

My index.html has split js files as follows:

<head>
  ....
  <!-- build:js js/app1.min.js -->
  <!-- js from lib -->
  <script src="bower_components/angular/angular.min.js"></script>
  <script src="bower_components/angular-route/angular-route.min.js"></script>

  <!-- js of this app -->
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>

  <!-- external js -->
  <script type="text/javascript" src="http://ift.tt/1lrRXYd"></script>
  <!-- endbuild -->
  ....
</head>

.....
<body>
...
  <!-- build:js js/app2.min.js -->

  <!-- js from lib -->
  <script src="bower_components/jquery/dist/jquery.min.js"></script>
  <!-- angular-animate provides search functionality -->

  <!-- js of this app -->      
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

  <!-- endbuild -->
  ....
</body>

As you can see, I tried to use two sets of js files. The reason to split is performance. How to use usemin in this case. I tried with following:

'useminPrepare': {
  'html': 'app/index.html'
},

'usemin': {
  'html': ['dist/index.html']
},

However, there is no folder/file created. But in index.html, those two sections are replaced appropriately by app1.min.js and app2.min.js

Moreover, I do not understand one thing that all examples are using concat and uglify in combination of usemin. The files in index.html which are already *.min.js eg. files included in bower_components folder, what happens to them?

Why is my ng-repeat acting like the object is empty?

Here is my controller code:

// Called automatically with the response of the YouTube API request.
window.onSearchResponse = function(response) {
    console.log(response); //Shows entire response data
    console.log(response.items[0].snippet.title); //shows video title
    console.log(response.items[0].id.videoId); //shows video Id
    console.log(response.items[0].snippet.thumbnails.medium.url); //shows video thumbnail
    $scope.videos = response.items;
    console.log($scope.videos); //This outputs an object with 5 Objects in it. Proof that the API is picking up something.
};

}]);

And here is the partial:

<ul>
    <li ng-repeat="video in videos">
    hey
    </li>
</ul>

Since i'm using the youtubeAPI, every search result brings back 5 results. console.log($scope.video) shows in the console the 5 objects, so I know it's being populated.

However whenever I go to my partial page and inspect element, the tags are completely empty. like the ng-repeat never ran.

Why would it not run? I should be seeing "hey" 5 times.

AngularJS page does not refresh from server

I have an AngularJS app. The server side is Go and uses Gorilla Web Toolkit mux and sessions packages. The Angular app has two forms on the main page, Sign In and Sign Up. The data is posted to Go using AngularJS $http.post as JSON and appropriate responses are sent back from the server as JSON. What I want to achieve is that two different pages should be served on the main page of the website depending on if the user is logged in or not. Currently, when I submit the details of the Sign In form and the server responds with an appropriate response, I reload the page, but AngularJS keeps showing the page with the forms and not the new page.

AngularJS Code

angular.module('app', [])

angular.module('app').controller('SignInController', ['$scope', '$http', function($scope, $http) {
    $scope.formData = {}

    $scope.signIn = function() {
        $http.post('/signIn', {
            email: $scope.formData.email,
            password: $scope.formData.password
        }).success(function(data) {
            console.log(data)
            if(data.ok == true) {
                window.location.reload(true)
            }
        })
    }
}])

Relevant Go Code Below, the SignInHandler gets called on a POST to "/signIn" and the IndexHandler gets called on a Get to "/".

type JsonResponse map[string]interface{}

func (jr JsonResponse) String() (output string) {
    b, err := json.Marshal(jr)
    if err != nil {
        output = ""
        return
    }
    output = string(b)
    return
}

func SignInHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := sessionStore.Get(r, "user-session")

    decoder := json.NewDecoder(r.Body)
    var user User
    err := decoder.Decode(&user)
    if err != nil {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Bad request"})
        return
    }

    if user.Email == "" || user.Password == "" {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "All fields are required"})
        return
    }

    userExists, u := user.Exists()
    if userExists == false {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
        return
    }

    err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(user.Password))
    if err != nil {
        fmt.Fprint(w, JsonResponse{"ok": false, "message": "Email and/or password in invalid"})
        return
    }

    session.Values["userId"] = u.Id.Hex()

    session.Save(r, w)

    fmt.Fprint(w, JsonResponse{"ok": true, "message": "Authentication Successful"})
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
    session, _ := sessionStore.Get(r, "promandi-user-session")

    if _, ok := session.Values["userId"]; ok {
        http.ServeFile(w, r, "./views/home.html")
    } else {
        http.ServeFile(w, r, "./views/index.html")
    }
}

angularjs ui-bootstrap 2 datepickers is error

i used uibootstraps datepicker,i write 2 in a page. 1 is starttime ,1 is endtime i want when i set starttime ,the endtimes min-date is start time. but when i click ,endtime will get empty in first time,and its ok in second time.

   <p class="input-group">
              <input  class="form-control" datepicker-popup ng-model="view.starttime" is-open="dateSet.opened.startTime" min-date="'2015-05-02'" max-date="'2015-06-22'" datepicker-options="dateSet.dateOptions" date-disabled="dateSet.disabled(date, mode)" ng-required="true" show-weeks="flase" />
              <span class="input-group-btn">
                <button type="button" class="btn btn-default" ng-click="dateSet.openFn($event,'startTime')"><i class="glyphicon glyphicon-calendar"></i></button>
              </span>
            </p>
 <p class="input-group">
                  <input  class="form-control" datepicker-popup ng-model="view.endtime" is-open="dateSet.opened.endTime" min-date="view.starttime" max-date="'2015-06-22'" datepicker-options="dateSet.dateOptions" date-disabled="dateSet.dateSet.disabled(date, mode)" ng-required="true" show-weeks="flase"/>
                  <span class="input-group-btn">
                    <button type="button" class="btn btn-default" ng-click="dateSet.openFn($event,'endTime')"><i class="glyphicon glyphicon-calendar"></i></button>
                  </span>
                </p>

Cannot set dialog width in ngDialog

I'm simply trying to set the width of the dialog box, and I haven't succeeded (yet). I have added a CSS class, but the width set is the one of the dialog shade.

.dialogwidth800 {
    width : 800px;
}
...
ngDialog.openConfirm({
    template: 'templateRemove',
    className: 'ngdialog-theme-default dialogwidth800',
    scope: $scope
}).then(

I have a fiddle here : http://ift.tt/1bFdxqo

Thanks a lot for your help !!!

G

set dynamic options on angular chosen

I am using Angular-chosen and I am unable to set dynamic options.

my jade

label.col-sm-2.control-label Tags
                .col-sm-10(ng-init='delegate.getCategories()')
                    select.chosen-select.form-control(chosen="", multiple, ng-model="tags", ng-change='delegate.getCategories()' data-ng-options='s.categoryName for s.categoryName in tagsList')

                .clearfix

My controller class

getCategories: function(){
                constantsService.getCategories($scope.category,this.onGetCategories,this.onFailure);
                alert($scope.category);
            },
            onGetCategories:function(response){
                $scope.tagsList=response.categories;
                alert(response);
            },
            onFailure:function(response){
                alert(response);
            }

on page load the init gets the categories form the backend and and sets in tagsList variable but its not there when the html loads.

Cookie creation through angularjs throws 403 through IIS in web farm

We have an application where we are using AngularJS for front end and Web API as back end (REST).

We are creating cookies using cookieStore to save client data. This scenario works well when there is only one server machine involved. But when there 2 machines used through load balancing then IIS throws 403 (Forbidden) status code.

When we create same cookie in WebAPI instead of in AngularJS code works well in Web Farm scenario.

We are using same machine key on both the servers in both the scenarios.

Can any one help me understand why does this happen and what should we do to avoid this?

How to implement basic Spring security (session management) for Single Page AngularJS application

I am currently building a single page AngularJS application which communicates via REST to a backend. The structure is as follow:

One Spring MVC WebApp project which contains all AngularJS pages and resources and all REST controllers.

A true backend which has services and repositories for backend communication, an API if you will. The REST calls will talk to these service (the second project is included as a dependency of the first one).

I have been thinking about this a lot but I can't seem to find anything that can help me. Basically I just need some security on this application. I'd like some kind of session management which is extremely simple:

  • user logs in, session id is created and stored in JS/cookie on website
  • when user would reload page/ come back later a check needs to be done to see if the session id is still valid
  • no calls should reach the controllers if the session id is not valid

This is the general idea of basic session managament, what would be the easiest way to get this implemented in a Spring MVC webapp (no JSP's, just angular and REST controllers).

Thanks in advance!

Show html in angular if $location matches

I am trying to get some html to show only on one of the paths in my app in angular, but cant seem to get the ng-if to function correctly.

Here is what I have

In Controller:

$scope.$on('$routeChangeStart', function() { 
    $scope.appLocation = $location.$$path;
});

HTML:

<div ng-if="{{appLocation}} == '/channels'">
    <!-- html to show -->
</div>

What am I doing wrong here, or is there a better way to do this?

how to set and get new data in angulajs

when adding products and price it was added in the table. how to set the added data and get the data in another view

routerApp.controller('products', function ($scope) {

$scope.items = [

];
    $scope.addRow = function(){    
    $scope.items.push({'Products':$scope.Products,'Price':$scope.Price});

 }