My question:
As in the title: The value defined in ng-init in angular cannot be obtained in the controller
Related codes:
<p class="container" ng-app="app" ng-controller="ctrl" ng-init="demo='风一样的男子'">
<h1>ng-init</h1>
<input ng-model="demo" type="text">
demo = {{demo}}
<button type="button" ng-click="demoClick()">button</button>
</p>
(function(angular) {
'use strict';
var app = angular.module('app', []).controller('ctrl', ctrl);
function ctrl ($scope, $http) {
console.log('直接获取: ' + $scope.demo); // undefined
$http.post('/demo', {
direction: $scope.demo // undefined
});
$scope.demoClick = function () {
console.log('click: ' + $scope.demo); // 风一样的男子
$http.post('/demo', {
direction: $scope.demo // 风一样的男子
});
};
}
}(angular));
WHY?
世界只因有你2017-05-15 17:07:49
This involves the compilation and linking process of each instruction. It should be noted that on the same node, if there is an ngController instruction, it will execute the compilation process before any other instructions (its priority is 500, while ngInit's priority is 450). Therefore, when executing the link function of ngController, which is the controller function we often see, ngInit has not completed the compilation process, so it naturally cannot obtain the value of demo.
http://stackoverflow.com/ques...
PHP中文网2017-05-15 17:07:49
If you want to access the demo at the location above. I think it should be used. $rootscope.demo or $parentscope.demo
The above problem should be a scope problem.