Very simple ng-model watches do not work

Here is the jsfiddle. http://jsfiddle.net/CLcfC/

the code

var app = angular.module('app',['']);

app.controller('TestCtrl',function($scope){
    $scope.text = 'Change Me';
    $scope.$watch('text',function(){
        alert('Changed !');
    });


})

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="app">
 <div ng-controller="TestCtrl">
     <input type="text" ng-model='text'/>
     <span>{{text}}</span>
  </div> 
</div>

I do not see the change in $scope.text. Please help. It is so simple, but what am I missing?

+4
source share
3 answers

Your JavaScript file is loaded after initializing AngularJS and therefore cannot find your module. To fix this, change the initialization to manual initialization.

First change your HTML code and remove the directive ng-app:

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div id="appRoot">
 <div ng-controller="TestCtrl">
     <input type="text" ng-model='text'/>
     <span>{{text}}</span>
  </div> 
</div>

Then go to your JavaScript and use the angular.bootstrap method to manually add your module:

var app = angular.module('app',[]);

app.controller('TestCtrl',function($scope){
    $scope.text = 'Change Me';
    $scope.$watch('text',function(){
        alert('Changed !');
    });
});

angular.element(document).ready(function() {
    angular.bootstrap(document.getElementById('appRoot'), ['app']);
});

AngularJS .

+3

, , []. (, , .)

var app = angular.module('app', []);

: http://jsfiddle.net/MWa66/

+6

! ! , , , angular UI-,

.state('app.monimes', {
      url: "/monimes",
      views: {
        'menuContent' :{
          templateUrl: "templates/monimes.html",
          controller: 'sampleCtrl'
        }
      }
    })

/***  *  * .  */

.controller('sampleCtrl',['$scope','sampleService', function($scope, $sampleService) {


     $scope.username="em";
       // Watch for changes on the username property.
// If there is a change, run the function

    $scope.$watch('username', function(newUsername) {
        // uses the $http service to call the GitHub API
        // //log it 
        $scope.log(newUsername);
        // and returns the resulting promise
            $sampleService.events(newUsername)
                  .success(function(data, status, headers) {
                              // the success function wraps the response in data
                              // so we need to call data.data to fetch the raw data
                     $scope.events = data.data;
                  });
    },true);
}
]);

<div>
     <label for="username">Type in a GitHub username</label>
     <input type="text" ng-model="username" placeholder="Enter a GitHub username, like a user" />
      <pre ng-show="username">{{ events }}</pre>
</div>

.

ng-controller="sampleCtrl" div : D

, , .

+1
source

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


All Articles