我的问题:
如题: angular中ng-init中定义值在控制器里面获取不到值
相关代码:
<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.