zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular] In angular world and out angular world

Angular in and out World
2023-09-14 08:59:21 时间
<html ng-app="nameApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js Example</title>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
    <script>
      var nameApp = angular.module('nameApp', []);
      nameApp.controller('NameCtrl', function ($scope){
        $scope.firstName = 'John';

        $scope.$watch('lastName', function(newValue, oldValue){
          console.log('new value is ' + newValue);
        });

        setTimeout(function(){
          $scope.lastName = 'Smith';
          $scope.$apply();    /*Without $scope.$apply(), it won't work*/
        }, 1000);
      });
    </script>
  </head>
  <body ng-controller="NameCtrl">
    First name:<input ng-model="firstName" type="text"/>
    <br>
    Last name:<input ng-model="lastName" type="text"/>
    <br>
    Hello {{firstName}} {{lastName}}
  </body>
</html>

Those pieces is outside angular world, if you don't have $scope.$apply, the lastname won't get updated.

        setTimeout(function(){
          $scope.lastName = 'Smith';
          $scope.$apply();    /*Without $scope.$apply(), it won't work*/
        }, 1000);