Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-init with condition statements

I have a Angular JS Application,

<div class="col-lg-12" ng-init="getTableData('{{URL::route('get_repair_category')}}')">

When Page loading the getTableData will execute, but I want to check a variable $rootScope.Dealer and switch the function name of initialization.

Eg : if $rootScope.Dealer value present I wanto execute the function named getDealerData

And If the value is not set need to execute the getTableData function.

How can I make this in anglar js template.

I just tried the ng-if, but its not working...

like image 556
Jishad Avatar asked Oct 24 '16 11:10

Jishad


People also ask

What does ng init do?

The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.

When Ng INIT is called?

x, ngInit is called when template is re-rendered. In other words “ng-init” is called, when I take turns back to a page. In Angular2, there is no “ng-init” but we can create a ways like this using the directive and ngOnInit class. Angular 2 provides life cycle hook ngOnInit by default.


2 Answers

You can use simple Javascript syntax in ng-init directive like this:

<div class="col-lg-12" ng-init="Dealer ? getDealerData('{{URL::route('get_repair_category')}}') : getTableData('{{URL::route('get_repair_category')}}')">

Here is a plnkr for you (I've changed backend route generation to text): https://plnkr.co/edit/CJOMT0g50BCWa3j02rcS?p=preview

like image 154
Hardy Rust Avatar answered Oct 18 '22 03:10

Hardy Rust


Try this

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $rootScope) {

  $rootScope.dealer = ["a", "b", "c"];

  $scope.getTableData = function(x) {
    return x;
  }
  $scope.getDelearData = function() {
    return $rootScope.dealer;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-init="data = getDelearData() || getTableData('table data')">
    {{data}}
  </div>
</div>
like image 2
Krupesh Kotecha Avatar answered Oct 18 '22 02:10

Krupesh Kotecha