Related recommendations: "angularjs Tutorial"
I believe that everyone will also encounter the problems I am encountering now when developing angularjs: Obviously the page has two-way data binding and the data has changed, but the view has not been refreshed.
Code example
<div ng-controller="testCtrl"> <p>{{name}}</p> <div ng-if="show"> <input type="text" ng-model="name"> </div> </div> <script> function testCtrl($scope){ $scope.show = true; $scope.name = 'xiao ming'; } </script>
As shown in the code, when we change the value of the input, the value of the variable name should change due to the change of the data. Changes are made through two-way binding and are consistent with the value of the input. However, no change in view actually occurs.
The reason is because ng-if will isolate the scope and create a new scope. As a result, scope.name is not a value in the same scope as the name in the input, so it cannot be changed.
Scope
Each Angular application has a root scope $rootScope by default. The root scope is at the top level and goes down from it. Hanging scopes at all levels.
Normally, the variables bound to ng-model in the page are defined in the corresponding Controller. If a variable is not defined in the current scope, JavaScript will look up through the prototype of the current Controller, which is scope inheritance.
Solution
<div ng-controller=“testCtrl"> <p>{{data.name}}</p> <div ng-if="show"> <input type="text" ng-model="data.name"> </div> </div> <script> function testCtrl($scope){ $scope.show = true; $scope.data = {}; $scope.data.name = 'xiao ming'; } </script>
ng-if actually isolates a scope. At this time, testCtrl is the parent scope, ng- if is equivalent to the child scope, at this time two-way data binding can be achieved by referencing data.
Scope in ng-if
In this case, the data of the two is the same reference to this object Modifications to properties can be reflected on two-level objects.
The actual situation is that not only the Controller can create a scope, instructions such as ng-if will also (implicitly) generate new scopes. To sum up, ng-if, ng-switch, ng-include and other things that can dynamically create an interface all have their own first-level scope. Therefore, object references should be used as much as possible during the development process.
For more knowledge about computer programming, please visit: Introduction to Programming! !
The above is the detailed content of Solution to angularjs data binding failure. For more information, please follow other related articles on the PHP Chinese website!