Aakash Aakash - 1 year ago 1377
AngularJS Question

Disable ui-sref based on a condition

Can you tell me a way to disable the submit button , which takes to a new state by

<a ui-sref="state">Submit</a>

The button should be enabled only when the form is valid .

ng-disabled with ui-sref does not work :

<form name="tickets">
<button ng-disabled="!canSave()"><a ui-sref="view">Submit</a></button>

canSave function inside app.js being:

$scope.canSave = function(){
return $scope.tickets.$dirty && $scope.tickets.$valid;

m59 m59
Answer Source

You could simply pair it with ng-click so that ng-disabled will work.

.controller('myCtrl', function($scope, $state) {
    // so that you can call `$state.go()` from your ng-click
    $scope.go = $state.go.bind($state);
<!-- call `go()` and pass the state you want to go to -->
<button ng-disabled="!canSave()" ng-click="go('view')>Submit</button>

Here's a more fancy way using a custom directive:

angular.module('myApp', ['ui.router'])
.config(function($stateProvider) {
  $stateProvider.state('home', {
    url: '/'
.controller('myCtrl', function() {
.directive('uiSrefIf', function($compile) {
  return {
    scope: {
      val: '@uiSrefVal',
      if: '=uiSrefIf'
    link: function($scope, $element, $attrs) {
      $scope.$watch('if', function(bool) {
        if (bool) {
          $element.attr('ui-sref', $scope.val);
        } else {
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.13/angular-ui-router.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <form name="form">
    <input ng-model="foo" ng-required="true">
    <button ng-disabled="form.$invalid">
      <a ui-sref-if="!form.$invalid" ui-sref-val="home">test</a>