小编典典

使用 ng-include 时失去作用域

all

我有这个模块路线:

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'});
}]);

主页 HTML:

<div ng-include src="views.partial1"></div>

partial1HTML:

<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 = "";
    };
...
}

addLine函数$scope.lineTextis 中undefined,这可以通过添加ng- controller="HomeCtrl"to来解决partial1.html,但是它会导致控制器被调用两次。我在这里想念什么?


阅读 121

收藏
2022-08-05

共1个答案

小编典典

这是因为ng- include它创建了一个新的子范围,所以没有$scope.lineText改变。我认为是this指当前的范围,所以this.lineText应该设置。

2022-08-05