In an Angular template, is there a way to throw an error if the variable is undefined?

In Angular templates, if the template has an undefined variable, it will fail.

Sample code below:

Controller:

angular.module('app').controller('MyCtrl', function($scope) {
  //nothing here
});

And the view:

<div ng-controller="MyCtrl">
  <p ng-click="doSomething()">{{ data }}</p>
  <input type="text" ng-modal="input">
</div>

None of the variables will be interpolated because they do not exist in $ scope. The omitted ng-modal( un ng-model) attribute will fail. This is undesirable development behavior.

Is there a way to change this so that errors are thrown? I would be fine with the monkey patch solution for Angular for this.

+4
source share
1 answer

, || . || . , :

<div ng-controller="MyCtrl">
  <p ng-click="doSomething()">{{ data || "Data is not defined" }}</p>
  <input type="text" ng-modal="input">
</div>

" " $scope.data. , , .

<div ng-controller="MyCtrl">
  <p ng-click="doSomething()">{{ data || handleEmptyData(data) || "Data is not defined and handleEmptyData() also returned undefined" }}</p>
  <input type="text" ng-modal="input">
</div>

$scope.handleEmptyData = function(data){
    if(!data){ alert("Error, data was " + JSON.stringify(data)); } };
+2

Source: https://habr.com/ru/post/1584577/


All Articles