Search code examples
javascriptangularjsangularjs-ng-if

ng-if not working with simple javascript


ng-if is not working when I change the values through simple javascript function.My function is getting called but the changes in values cannot be seen in view. Please refer below code.

HTML

<div id="span" ng-app='MyModule' ng-cloak ng-controller="MyController">

<div ng-if="!bool">
  This is for true
</div>
<div ng-if="bool">
  This is False
</div>
{{bool}}
<br>
<input type="submit" ng-click = "myfunction('test')" value="ng-if button">
</div>
<input type="submit" onClick = "check1()" value="simple JS button">

JS

angular.module('MyModule', [])
.controller('MyController', function ($scope) {
$scope.bool = true;
$scope.myfunction = function (data) {
    $scope.bool = !$scope.bool;
};
});
function check1() {
    angular.element(document.getElementById('span')).scope().myfunction('test');
}

When I use ng-click button it changes value of bool changes, but same doesn't happens with simple JS button . Actually I am implementing Angular in a page that already uses jQuery, so I need to use simple JS button.

JS Fiddle : JS Fiddle


Solution

  • At first, ng-click is able to parse an angular expression.

    Second, it handles the reference to the current scope and performs a call to $scope.$apply to notify any watchers to update. If you would add a call to angular.element(document.getElementById('span')).scope().$apply() in your function, it should work as expected.