使用ng-include时丢失范围 [英] Losing scope when using ng-include
本文介绍了使用ng-include时丢失范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var mainModule = angular.module('lpConnect',[])。 $('/ home',{template:'views / home.html',控制器:HomeCtrl,'b $ b config(['$ routeProvider',function($ routeProvider){
$ routeProvider。 })。
when('/ admin',{template:'views / admin.html',controller:AdminCtrl})。
otherwise({redirectTo:'/ connect'});
}]);
首页HTML:
< div ng-include src =views.partial1>< / div>
partial1
HTML:
< form ng-submit =addLine()>
< input type =textng-model =lineTextsize =30placeholder =在此输入您的信息>
< / form>
HomeCtrl
:
函数HomeCtrl($ scope,$ location,$ window,$ http,Common){
...
$ scope。 views = {
partial1:views / partial1.html
};
$ scope.addLine = function(){
$ scope.chat.addLine($ scope.lineText);
$ scope.lines.push({text:$ scope.lineText});
$ scope.lineText =;
};
...
在 addLine function
$ scope.lineText
是 undefined
,可以通过添加 ng-controller =HomeCtrl
to partial1.html
,但它会导致控制器被调用两次。我在这里错过了什么?
解决方案
这是因为 ng-include
它创建一个新的子范围,所以 $ scope.lineText
不会改变。我认为这个
指的是当前范围,所以应该设置 this.lineText
。
I have this module routes:
var mainModule = angular.module('lpConnect', []).
config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {template:'views/home.html', controller:HomeCtrl}).
when('/admin', {template:'views/admin.html', controller:AdminCtrl}).
otherwise({redirectTo:'/connect'});
}]);
Home HTML:
<div ng-include src="views.partial1"></div>
partial1
HTML:
<form ng-submit="addLine()">
<input type="text" ng-model="lineText" size="30" placeholder="Type your message here">
</form>
HomeCtrl
:
function HomeCtrl($scope, $location, $window, $http, Common) {
...
$scope.views = {
partial1:"views/partial1.html"
};
$scope.addLine = function () {
$scope.chat.addLine($scope.lineText);
$scope.lines.push({text:$scope.lineText});
$scope.lineText = "";
};
...
}
In the addLine
function $scope.lineText
is undefined
, this can be resolved by adding ng-controller="HomeCtrl"
to partial1.html
, however it causes the controller to be called twice. What am I missing here?
解决方案
This is because of ng-include
which creates a new child scope, so $scope.lineText
isn’t changed. I think that this
refers to the current scope, so this.lineText
should be set.
这篇关于使用ng-include时丢失范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文